From f41eda63ddf472a089b405345ee1c2f53284ab30 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 01:05:40 +0000 Subject: [PATCH 01/73] UI: mode buttons at the right end of the top bar, tool controls scroll when they don't fit The Painting, Bake and Render buttons move from the left tool shelf to the right end of the top bar, which now shows in every mode. The view and mode buttons keep their place; the tool controls scroll in their own strip with arrow buttons and the horizontal wheel instead of drawing over them. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/toolbar.rs | 243 ++++++++++++++++++++------------- crates/ui-egui/src/viewport.rs | 2 +- crates/ui-egui/src/widgets.rs | 14 +- 3 files changed, 160 insertions(+), 99 deletions(-) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 2c900ed3..49553015 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1,5 +1,5 @@ //! The context tool bar (brush size, flow, stroke opacity, spacing, lazy mouse, symmetry, view -//! toggles), the vertical tool shelf, the right icon rail and the status bar. +//! toggles, mode buttons), the vertical tool shelf, the right icon rail and the status bar. use egui::{RichText, vec2}; use egui_phosphor::regular as ic; @@ -12,7 +12,7 @@ use crate::i18n::{tr, trf}; use crate::keymap::tip; use crate::state::{Mode, ViewLayout}; use crate::theme::{GUTTER, Tokens, card}; -use crate::widgets::{bar_slider, icon_button}; +use crate::widgets::{bar_slider, icon_button, icon_button_without_tooltip}; pub fn tool_icon(t: Tool) -> &'static str { match t { @@ -34,84 +34,15 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, egui::Margin::symmetric(8, 0), |ui| { ui.horizontal_centered(|ui| { ui.spacing_mut().item_spacing.x = 10.0; - let tool = app.session.tool.tool; - ui.label(RichText::new(tool_icon(tool)).size(15.0).color(tokens.text_strong)).on_hover_text(tool.label()); - let brush = &mut app.session.tool.brush; - match tool { - Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path => { - let mut size = brush.size / 0.25 * 100.0; - if bar_slider(ui, tr("Size"), &mut size, 0.05..=100.0, 110.0).changed() { - brush.size = (size / 100.0 * 0.25).clamp(0.0005, 0.25); - } - let mut flow = brush.flow * 100.0; - if bar_slider(ui, tr("Flow"), &mut flow, 0.0..=100.0, 100.0).changed() { - brush.flow = flow / 100.0; - } - let mut opacity = brush.opacity * 100.0; - if bar_slider(ui, tr("Stroke opacity"), &mut opacity, 0.0..=100.0, 110.0).changed() { - brush.opacity = opacity / 100.0; - } - let mut spacing = brush.spacing * 100.0; - if bar_slider(ui, tr("Spacing"), &mut spacing, 1.0..=200.0, 100.0).changed() { - brush.spacing = spacing / 100.0; - } - ui.separator(); - let lazy_on = brush.lazy > 0.0; - if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, 24.0).clicked() { - brush.lazy = if lazy_on { 0.0 } else { 20.0 }; - } - if lazy_on { - let mut distance = brush.lazy; - if bar_slider(ui, tr("Distance"), &mut distance, 1.0..=200.0, 90.0).changed() { - brush.lazy = distance; - } - } - ui.separator(); - if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), brush.symmetry.x, 24.0).clicked() { - brush.symmetry.x = !brush.symmetry.x; - } - if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), brush.symmetry.y, 24.0).clicked() { - brush.symmetry.y = !brush.symmetry.y; - } - if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, 24.0).clicked() { - brush.particles.enabled = !brush.particles.enabled; - } - if tool == Tool::Smudge { - ui.separator(); - let mut strength = app.session.tool.smudge_strength * 100.0; - if bar_slider(ui, tr("Strength"), &mut strength, 0.0..=100.0, 100.0).changed() { - app.session.tool.smudge_strength = (strength / 100.0).clamp(0.0, 1.0); - } - } - if tool == Tool::Clone && app.session.tool.clone_source.is_none() { - ui.separator(); - ui.label(RichText::new(tr("Hold V and click the mesh to set the clone source")).color(tokens.text_dim)); - } - if tool == Tool::Path { - ui.separator(); - path_controls(app, ui); - } - } - Tool::PolygonFill => { - use texturecraft_engine::FillMode; - for (fill_mode, icon, tip) in [ - (FillMode::Triangle, ic::POLYGON, tr("Triangle fill")), - (FillMode::UvIsland, ic::SHAPES, tr("UV island fill")), - (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), - ] { - if icon_button(ui, icon, tip, app.session.tool.fill_mode == fill_mode, 24.0).clicked() { - app.session.tool.fill_mode = fill_mode; - } - } - } - Tool::ColorPicker => { - ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tokens.text_dim)); - } - Tool::GeometryMask => { - ui.label(RichText::new(tr("Click a mesh part to show or hide the selected layer on it.")).color(tokens.text_dim)); - } - } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + mode_buttons(app, ui); + + // Bake and Render modes have no brush, so their bar holds only the mode buttons + if app.ui.mode != Mode::Painting { + return; + } + + ui.separator(); if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, 24.0).clicked() { app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); } @@ -131,12 +62,153 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let mode = if checker { "material" } else { "uvChecker" }; app.run("viewport.view", json!({"mode": mode})); } + ui.separator(); + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| scrolling_tool_controls(app, ui, &tokens)); }); }); }); }); } +/// The tool's controls, in a strip with scroll arrows when they don't fit +fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) { + let strip_width = ui.available_width(); + let overflow_id = egui::Id::unique("tool_controls_overflow"); + let overflowing = ui.data(|data| data.get_temp::(overflow_id)).unwrap_or(false); + + // A positive delta moves the content right, revealing its start + let arrow_scroll_step = strip_width / 2.0; + let mut scroll_delta = 0.0; + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_LEFT, "Scroll left", false, 24.0).clicked() { + scroll_delta = arrow_scroll_step; + } + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_RIGHT, "Scroll right", false, 24.0).clicked() { + scroll_delta = -arrow_scroll_step; + } + + let scroll_area = egui::ScrollArea::horizontal().id_salt("tool_controls").scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden); + let output = ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + scroll_area.show(ui, |ui| { + ui.scroll_with_delta(vec2(scroll_delta, 0.0)); + ui.horizontal_centered(|ui| tool_controls(app, ui, tokens)); + }) + }); + + // The arrows take room from the strip, so measure the overflow against its full width + let overflows_now = output.inner.content_size.x > strip_width; + if overflows_now != overflowing { + ui.data_mut(|data| data.insert_temp(overflow_id, overflows_now)); + ui.ctx().request_repaint(); + } + }); +} + +/// The selected tool's icon and its settings +fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) { + // Brush radius limits as a fraction of the mesh diagonal; the slider shows the maximum as 100 + const MAX_BRUSH_SIZE: f32 = 0.25; + const MIN_BRUSH_SIZE: f32 = 0.0005; + const DEFAULT_LAZY_DISTANCE: f32 = 20.0; + const TOOL_ICON_SIZE: f32 = 15.0; + + let tool = app.session.tool.tool; + ui.label(RichText::new(tool_icon(tool)).size(TOOL_ICON_SIZE).color(tokens.text_strong)).on_hover_text(tr(tool.label())); + + let brush = &mut app.session.tool.brush; + match tool { + Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path => { + let mut size = brush.size / MAX_BRUSH_SIZE * 100.0; + if bar_slider(ui, tr("Size"), &mut size, 0.05..=100.0, 110.0).changed() { + brush.size = (size / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + } + let mut flow = brush.flow * 100.0; + if bar_slider(ui, tr("Flow"), &mut flow, 0.0..=100.0, 100.0).changed() { + brush.flow = flow / 100.0; + } + let mut opacity = brush.opacity * 100.0; + if bar_slider(ui, tr("Stroke opacity"), &mut opacity, 0.0..=100.0, 110.0).changed() { + brush.opacity = opacity / 100.0; + } + let mut spacing = brush.spacing * 100.0; + if bar_slider(ui, tr("Spacing"), &mut spacing, 1.0..=200.0, 100.0).changed() { + brush.spacing = spacing / 100.0; + } + + ui.separator(); + let lazy_on = brush.lazy > 0.0; + if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, 24.0).clicked() { + brush.lazy = if lazy_on { 0.0 } else { DEFAULT_LAZY_DISTANCE }; + } + if lazy_on { + let mut distance = brush.lazy; + if bar_slider(ui, tr("Distance"), &mut distance, 1.0..=200.0, 90.0).changed() { + brush.lazy = distance; + } + } + + ui.separator(); + if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), brush.symmetry.x, 24.0).clicked() { + brush.symmetry.x = !brush.symmetry.x; + } + if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), brush.symmetry.y, 24.0).clicked() { + brush.symmetry.y = !brush.symmetry.y; + } + if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, 24.0).clicked() { + brush.particles.enabled = !brush.particles.enabled; + } + + if tool == Tool::Smudge { + ui.separator(); + let mut strength = app.session.tool.smudge_strength * 100.0; + if bar_slider(ui, tr("Strength"), &mut strength, 0.0..=100.0, 100.0).changed() { + app.session.tool.smudge_strength = (strength / 100.0).clamp(0.0, 1.0); + } + } + if tool == Tool::Clone && app.session.tool.clone_source.is_none() { + ui.separator(); + ui.label(RichText::new(tr("Hold V and click the mesh to set the clone source")).color(tokens.text_dim)); + } + if tool == Tool::Path { + ui.separator(); + path_controls(app, ui); + } + } + Tool::PolygonFill => { + use texturecraft_engine::FillMode; + for (fill_mode, icon, tooltip) in [ + (FillMode::Triangle, ic::POLYGON, tr("Triangle fill")), + (FillMode::UvIsland, ic::SHAPES, tr("UV island fill")), + (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), + ] { + if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, 24.0).clicked() { + app.session.tool.fill_mode = fill_mode; + } + } + } + Tool::ColorPicker => { + ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tokens.text_dim)); + } + Tool::GeometryMask => { + ui.label(RichText::new(tr("Click a mesh part to show or hide the selected layer on it.")).color(tokens.text_dim)); + } + } +} + +/// Bake, Painting and Rendering mode buttons for a right-to-left layout, so Rendering is added first +fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + for (mode, icon, label, command) in [ + (Mode::Rendering, ic::APERTURE, tr("Rendering (path traced)"), "ui.mode.render"), + (Mode::Painting, ic::PALETTE, tr("Painting"), "ui.mode.paint"), + (Mode::Baking, ic::ATOM, tr("Bake Mesh Maps"), "ui.mode.bake"), + ] { + if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, 24.0).clicked() { + crate::menus::invoke(app, &ui.ctx().clone(), command); + } + } +} + /// Path tool options and actions (top bar and properties). pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let path = &mut app.session.tool.path; @@ -165,19 +237,6 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { egui::Panel::left("tool_shelf").resizable(false).exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { card(ui, &tokens, egui::Margin { left: GUTTER, right: 0, top: GUTTER, bottom: GUTTER }, egui::Margin::symmetric(3, 6), |ui| { ui.spacing_mut().item_spacing.y = 3.0; - for (mode, icon, label, command) in [ - (Mode::Painting, ic::PALETTE, tr("Painting"), "ui.mode.paint"), - (Mode::Baking, ic::ATOM, tr("Bake Mesh Maps"), "ui.mode.bake"), - (Mode::Rendering, ic::APERTURE, tr("Rendering (path traced)"), "ui.mode.render"), - ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, 28.0).clicked() { - crate::menus::invoke(app, &ui.ctx().clone(), command); - } - } - - ui.add_space(6.0); - ui.separator(); - ui.add_space(6.0); ui.add_enabled_ui(app.ui.mode == Mode::Painting, |ui| { for tool in Tool::ALL { let selected = app.ui.mode == Mode::Painting && app.session.tool.tool == tool; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index db50b2db..da60a42d 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -43,7 +43,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { !texture_set.bake.high_poly.use_low_as_high && texture_set.bake.cage.kind == texturecraft_engine::core::CageType::DistanceBased }); app.ui.bake_paint_brush.on = bake_painting; - if mode == crate::state::Mode::Painting && !app.ui.hide_ui { + if !app.ui.hide_ui { crate::toolbar::paint_bar(app, ui); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index eb3a8eb4..1dd4046e 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -177,6 +177,11 @@ pub fn elided(painter: &egui::Painter, text: impl Into, size: f32, color /// A square icon button (Phosphor glyph) in a rounded tool well: `selected` sits in the accent /// tinted well (the shared Craft icon button, `craft_ui::buttons`). pub fn icon_button(ui: &mut Ui, icon: &str, tooltip: &str, selected: bool, size: f32) -> Response { + icon_button_without_tooltip(ui, icon, tooltip, selected, size).on_hover_text(tooltip) +} + +/// An `icon_button` with no tooltip, whose `label` still names it for screen readers +pub fn icon_button_without_tooltip(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { let tk = Tokens::get(ui.ctx()); let well = |fill, icon| ButtonVisuals { fill, stroke: Stroke::NONE, icon }; let style = IconButtonStyle { @@ -187,12 +192,9 @@ pub fn icon_button(ui: &mut Ui, icon: &str, tooltip: &str, selected: bool, size: corner_radius: CornerRadius::same(6), focus_stroke: Stroke::new(1.0, tk.accent), }; - IconButton::new(tooltip, vec2(size, size), &style) - .selected(selected) - .show(ui, |ui, rect, color| { - ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * 0.62), color); - }) - .on_hover_text(tooltip) + IconButton::new(label, vec2(size, size), &style).selected(selected).show(ui, |ui, rect, color| { + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * 0.62), color); + }) } /// A flat button filled with the accent, white lettering (a dialog's main action). From e072a6a5465552378a2b71c22973c4601160ca5a Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 01:22:59 +0000 Subject: [PATCH 02/73] Document the top bar function Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/toolbar.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 49553015..9f04df4c 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -28,6 +28,7 @@ pub fn tool_icon(t: Tool) -> &'static str { } } +/// The top bar: the tool's controls, the view buttons and the mode buttons (only the mode buttons outside Painting) pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let tokens = Tokens::get(ui.ctx()); egui::Panel::top("paint_bar").exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { From 70b7029b662b7b2debeed93c6a6a0ec8d5d39226 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 4 Nov 2026 21:06:18 -0500 Subject: [PATCH 03/73] Fix toolbar overflow in narrow viewports Keep mode buttons accessible while view controls join the scrolling strip when space is tight. Respect the remaining clip width, simplify the layout, translate view hints, and add toolbar interaction and visual checks. --- crates/ui-egui/src/toolbar.rs | 123 +++++++++++++++-------- crates/ui-egui/src/widgets.rs | 16 +-- crates/ui-egui/tests/toolbar.rs | 171 ++++++++++++++++++++++++++++++++ 3 files changed, 260 insertions(+), 50 deletions(-) create mode 100644 crates/ui-egui/tests/toolbar.rs diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 9f04df4c..a075840d 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1,5 +1,4 @@ -//! The context tool bar (brush size, flow, stroke opacity, spacing, lazy mouse, symmetry, view -//! toggles, mode buttons), the vertical tool shelf, the right icon rail and the status bar. +//! Context controls, view and mode buttons, tool shelf, icon rail and status bar use egui::{RichText, vec2}; use egui_phosphor::regular as ic; @@ -14,6 +13,11 @@ use crate::state::{Mode, ViewLayout}; use crate::theme::{GUTTER, Tokens, card}; use crate::widgets::{bar_slider, icon_button, icon_button_without_tooltip}; +const BAR_BUTTON_SIZE: f32 = 24.0; +const BAR_SPACING: f32 = 10.0; +const COMPACT_BAR_SPACING: f32 = 4.0; +const BAR_SEPARATOR_WIDTH: f32 = 6.0; + pub fn tool_icon(t: Tool) -> &'static str { match t { Tool::Paint => ic::PAINT_BRUSH, @@ -28,51 +32,70 @@ pub fn tool_icon(t: Tool) -> &'static str { } } -/// The top bar: the tool's controls, the view buttons and the mode buttons (only the mode buttons outside Painting) +/// Keep mode buttons visible, with painting controls scrolling as space runs out pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let tokens = Tokens::get(ui.ctx()); egui::Panel::top("paint_bar").exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, egui::Margin::symmetric(8, 0), |ui| { - ui.horizontal_centered(|ui| { - ui.spacing_mut().item_spacing.x = 10.0; - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - mode_buttons(app, ui); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mode_width = 3.0 * BAR_BUTTON_SIZE + 2.0 * BAR_SPACING; + let separator_width = BAR_SEPARATOR_WIDTH + 2.0 * BAR_SPACING; + // Leave room for both scroll arrows and at least one button of content + let minimum_strip_width = 3.0 * BAR_BUTTON_SIZE + 2.0 * BAR_SPACING; + let scroll_views = ui.available_width() < mode_width + view_buttons_width(BAR_SPACING) + 2.0 * separator_width + minimum_strip_width; + ui.spacing_mut().item_spacing.x = if scroll_views { COMPACT_BAR_SPACING } else { BAR_SPACING }; + mode_buttons(app, ui); - // Bake and Render modes have no brush, so their bar holds only the mode buttons - if app.ui.mode != Mode::Painting { - return; - } + if app.ui.mode != Mode::Painting { + return; + } - ui.separator(); - if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, 24.0).clicked() { - app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); - } - ui.separator(); - for (layout, icon, label, id) in [ - (ViewLayout::Only2D, ic::SQUARE, "2D view only", "ui.layout.2d"), - (ViewLayout::Only3D, ic::CUBE, "3D view only", "ui.layout.3d"), - (ViewLayout::Split, ic::COLUMNS, "3D/2D views", "ui.layout.split"), - ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, id), app.ui.layout == layout, 24.0).clicked() { - app.ui.layout = layout; - } - } - ui.separator(); - let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; - if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, 24.0).clicked() { - let mode = if checker { "material" } else { "uvChecker" }; - app.run("viewport.view", json!({"mode": mode})); - } - ui.separator(); - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| scrolling_tool_controls(app, ui, &tokens)); + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + if !scroll_views { + view_buttons(app, ui); + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + } + + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + scrolling_tool_controls(app, ui, &tokens, scroll_views); }); }); }); }); } -/// The tool's controls, in a strip with scroll arrows when they don't fit -fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) { +fn view_buttons_width(spacing: f32) -> f32 { + // Five icons, two separators and the six gaps between them + 5.0 * BAR_BUTTON_SIZE + 2.0 * BAR_SEPARATOR_WIDTH + 6.0 * spacing +} + +/// View buttons in a right-to-left layout, with the screenshot button at the end +fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, BAR_BUTTON_SIZE).clicked() { + app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); + } + + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + for (layout, icon, label, command) in [ + (ViewLayout::Only2D, ic::SQUARE, "2D view only", "ui.layout.2d"), + (ViewLayout::Only3D, ic::CUBE, "3D view only", "ui.layout.3d"), + (ViewLayout::Split, ic::COLUMNS, "3D/2D views", "ui.layout.split"), + ] { + if icon_button(ui, icon, &tip(&app.ui.keymap, tr(label), command), app.ui.layout == layout, BAR_BUTTON_SIZE).clicked() { + crate::menus::invoke(app, &ui.ctx().clone(), command); + } + } + + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; + if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, BAR_BUTTON_SIZE).clicked() { + let mode = if checker { "material" } else { "uvChecker" }; + app.run("viewport.view", json!({"mode": mode})); + } +} + +/// Scroll tool controls and, in narrow viewports, the view buttons +fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, scroll_views: bool) { let strip_width = ui.available_width(); let overflow_id = egui::Id::unique("tool_controls_overflow"); let overflowing = ui.data(|data| data.get_temp::(overflow_id)).unwrap_or(false); @@ -80,20 +103,30 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: // A positive delta moves the content right, revealing its start let arrow_scroll_step = strip_width / 2.0; let mut scroll_delta = 0.0; - if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_LEFT, "Scroll left", false, 24.0).clicked() { + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_LEFT, "Scroll left", false, BAR_BUTTON_SIZE).clicked() { scroll_delta = arrow_scroll_step; } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_RIGHT, "Scroll right", false, 24.0).clicked() { + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_RIGHT, "Scroll right", false, BAR_BUTTON_SIZE).clicked() { scroll_delta = -arrow_scroll_step; } - let scroll_area = egui::ScrollArea::horizontal().id_salt("tool_controls").scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden); + let scroll_area = egui::ScrollArea::horizontal() + .id_salt("tool_controls") + .min_scrolled_width(0.0) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden); let output = ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { scroll_area.show(ui, |ui| { ui.scroll_with_delta(vec2(scroll_delta, 0.0)); - ui.horizontal_centered(|ui| tool_controls(app, ui, tokens)); + ui.horizontal_centered(|ui| { + tool_controls(app, ui, tokens); + if scroll_views { + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + let size = vec2(view_buttons_width(ui.spacing().item_spacing.x), ui.available_height()); + ui.allocate_ui_with_layout(size, egui::Layout::right_to_left(egui::Align::Center), |ui| view_buttons(app, ui)); + } + }); }) }); @@ -111,7 +144,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) // Brush radius limits as a fraction of the mesh diagonal; the slider shows the maximum as 100 const MAX_BRUSH_SIZE: f32 = 0.25; const MIN_BRUSH_SIZE: f32 = 0.0005; - const DEFAULT_LAZY_DISTANCE: f32 = 20.0; + const DEFAULT_LAZY_DISTANCE_PX: f32 = 20.0; const TOOL_ICON_SIZE: f32 = 15.0; let tool = app.session.tool.tool; @@ -124,14 +157,17 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) if bar_slider(ui, tr("Size"), &mut size, 0.05..=100.0, 110.0).changed() { brush.size = (size / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } + let mut flow = brush.flow * 100.0; if bar_slider(ui, tr("Flow"), &mut flow, 0.0..=100.0, 100.0).changed() { brush.flow = flow / 100.0; } + let mut opacity = brush.opacity * 100.0; if bar_slider(ui, tr("Stroke opacity"), &mut opacity, 0.0..=100.0, 110.0).changed() { brush.opacity = opacity / 100.0; } + let mut spacing = brush.spacing * 100.0; if bar_slider(ui, tr("Spacing"), &mut spacing, 1.0..=200.0, 100.0).changed() { brush.spacing = spacing / 100.0; @@ -140,7 +176,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) ui.separator(); let lazy_on = brush.lazy > 0.0; if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, 24.0).clicked() { - brush.lazy = if lazy_on { 0.0 } else { DEFAULT_LAZY_DISTANCE }; + brush.lazy = if lazy_on { 0.0 } else { DEFAULT_LAZY_DISTANCE_PX }; } if lazy_on { let mut distance = brush.lazy; @@ -167,10 +203,12 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) app.session.tool.smudge_strength = (strength / 100.0).clamp(0.0, 1.0); } } + if tool == Tool::Clone && app.session.tool.clone_source.is_none() { ui.separator(); ui.label(RichText::new(tr("Hold V and click the mesh to set the clone source")).color(tokens.text_dim)); } + if tool == Tool::Path { ui.separator(); path_controls(app, ui); @@ -178,6 +216,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) } Tool::PolygonFill => { use texturecraft_engine::FillMode; + for (fill_mode, icon, tooltip) in [ (FillMode::Triangle, ic::POLYGON, tr("Triangle fill")), (FillMode::UvIsland, ic::SHAPES, tr("UV island fill")), @@ -204,7 +243,7 @@ fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { (Mode::Painting, ic::PALETTE, tr("Painting"), "ui.mode.paint"), (Mode::Baking, ic::ATOM, tr("Bake Mesh Maps"), "ui.mode.bake"), ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, 24.0).clicked() { + if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, BAR_BUTTON_SIZE).clicked() { crate::menus::invoke(app, &ui.ctx().clone(), command); } } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 1dd4046e..72853550 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -174,24 +174,24 @@ pub fn elided(painter: &egui::Painter, text: impl Into, size: f32, color painter.layout_job(job) } -/// A square icon button (Phosphor glyph) in a rounded tool well: `selected` sits in the accent -/// tinted well (the shared Craft icon button, `craft_ui::buttons`). +/// A square Phosphor icon button with a tooltip and an accent well when selected pub fn icon_button(ui: &mut Ui, icon: &str, tooltip: &str, selected: bool, size: f32) -> Response { icon_button_without_tooltip(ui, icon, tooltip, selected, size).on_hover_text(tooltip) } /// An `icon_button` with no tooltip, whose `label` still names it for screen readers pub fn icon_button_without_tooltip(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let well = |fill, icon| ButtonVisuals { fill, stroke: Stroke::NONE, icon }; let style = IconButtonStyle { - normal: well(Color32::TRANSPARENT, tk.text), - hovered: well(tk.row_hover, tk.text_strong), - pressed: Some(well(tk.tool_active, tk.text_strong)), - selected: well(tk.tool_active, tk.text_strong), + normal: well(Color32::TRANSPARENT, tokens.text), + hovered: well(tokens.row_hover, tokens.text_strong), + pressed: Some(well(tokens.tool_active, tokens.text_strong)), + selected: well(tokens.tool_active, tokens.text_strong), corner_radius: CornerRadius::same(6), - focus_stroke: Stroke::new(1.0, tk.accent), + focus_stroke: Stroke::new(1.0, tokens.accent), }; + IconButton::new(label, vec2(size, size), &style).selected(selected).show(ui, |ui, rect, color| { ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * 0.62), color); }) diff --git a/crates/ui-egui/tests/toolbar.rs b/crates/ui-egui/tests/toolbar.rs new file mode 100644 index 00000000..fc5c295a --- /dev/null +++ b/crates/ui-egui/tests/toolbar.rs @@ -0,0 +1,171 @@ +//! Toolbar layout and input coverage + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::{Session, Tool}; +use texturecraft_ui_egui::state::Mode; +use texturecraft_ui_egui::{TextureCraftApp, theme, toolbar}; + +fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> { + let session = Session::new_project("Toolbar", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let context = eframe::CreationContext::_new_kittest(egui::Context::default()); + let mut app = TextureCraftApp::new(&context, session); + app.session.tool.tool = tool; + app.session.tool.brush.lazy = 20.0; + let mut harness = + Harness::builder().with_size(egui::vec2(width, 200.0)).with_context_setup(theme::install).build_ui_state(|ui, app| toolbar::paint_bar(app, ui), app); + harness.run_steps(4); + harness +} + +fn size_label(harness: &Harness<'_, TextureCraftApp>) -> (egui::Pos2, egui::Rect) { + harness + .output() + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == "Size" => Some((text.pos, shape.clip_rect)), + _ => None, + }) + .unwrap() +} + +#[test] +fn narrow_toolbars_keep_scroll_arrows_and_mode_buttons_separate() { + let mut harness = toolbar_harness(700.0, Tool::Path); + for width in [500.0, 450.0, 400.0, 350.0, 240.0, 200.0] { + harness.set_size(egui::vec2(width, 200.0)); + harness.run_steps(4); + let left = harness.get_by_label("Scroll left").rect(); + let right = harness.get_by_label("Scroll right").rect(); + let bake = harness.get_by_label("Bake Mesh Maps (F8)").rect(); + let (_, clip) = size_label(&harness); + assert!(left.right() <= right.left(), "arrows overlap at width {width}: {left:?}, {right:?}"); + assert!(right.right() < bake.left(), "scrolling overlaps the mode buttons at width {width}"); + assert!(clip.left() >= left.right() && clip.right() <= right.left(), "content covers an arrow at width {width}: {clip:?}"); + assert!(harness.ctx.content_rect().contains_rect(left) && harness.ctx.content_rect().contains_rect(bake)); + } +} + +#[test] +fn arrows_and_wheel_scroll_without_changing_the_brush() { + let mut harness = toolbar_harness(700.0, Tool::Path); + let brush = harness.state().session.tool.brush.clone(); + let start = size_label(&harness).0.x; + harness.get_by_label("Scroll right").click(); + harness.run_steps(30); + let scrolled = size_label(&harness).0.x; + assert!(scrolled < start - 50.0); + + harness.get_by_label("Scroll left").click(); + harness.run_steps(30); + assert!((size_label(&harness).0.x - start).abs() < 1.0); + + let (_, clip) = size_label(&harness); + harness.hover_at(clip.center()); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(-100.0, 0.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(30); + assert!(size_label(&harness).0.x < start - 50.0); + assert_eq!(harness.state().session.tool.brush, brush); +} + +#[test] +fn shorter_tools_and_wider_windows_remove_the_arrows() { + let mut harness = toolbar_harness(700.0, Tool::Path); + harness.get_by_label("Scroll right").click(); + harness.run_steps(30); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + harness.state_mut().session.tool.fill_mode = texturecraft_engine::FillMode::Mesh; + harness.run_steps(4); + assert!(harness.query_by_label("Scroll right").is_none()); + let triangle = harness.get_by_label("Triangle fill").rect(); + harness.get_by_label("Triangle fill").click(); + harness.run_steps(2); + assert!(harness.ctx.content_rect().contains_rect(triangle)); + assert_eq!(harness.state().session.tool.fill_mode, texturecraft_engine::FillMode::Triangle); + + harness.state_mut().session.tool.tool = Tool::Path; + harness.set_size(egui::vec2(1600.0, 200.0)); + harness.run_steps(4); + assert!(harness.query_by_label("Scroll right").is_none()); + let (position, clip) = size_label(&harness); + assert!(clip.contains(position)); +} + +#[test] +fn compact_view_buttons_can_be_scrolled_into_view_and_clicked() { + let mut harness = toolbar_harness(400.0, Tool::Path); + for _ in 0..20 { + let left = harness.get_by_label("Scroll left").rect(); + let right = harness.get_by_label("Scroll right").rect(); + let visible = harness.query_by_label("UV checker").is_some_and(|node| node.rect().left() > left.right() && node.rect().right() < right.left()); + if visible { + harness.get_by_label("UV checker").click(); + harness.run_steps(3); + assert_eq!(harness.state().session.view, texturecraft_engine::ViewMode::UvChecker); + return; + } + + harness.get_by_label("Scroll right").click(); + harness.run_steps(30); + } + + panic!("the view buttons never became accessible"); +} + +#[test] +fn mode_buttons_keep_their_order_and_dispatch_commands() { + let mut harness = toolbar_harness(700.0, Tool::Paint); + for (label, mode) in [("Bake Mesh Maps (F8)", Mode::Baking), ("Rendering (path traced) (F10)", Mode::Rendering), ("Painting (F9)", Mode::Painting)] { + let bake = harness.get_by_label("Bake Mesh Maps (F8)").rect(); + let paint = harness.get_by_label("Painting (F9)").rect(); + let render = harness.get_by_label("Rendering (path traced) (F10)").rect(); + assert!(bake.right() < paint.left() && paint.right() < render.left()); + harness.get_by_label(label).click(); + harness.run_steps(3); + assert_eq!(harness.state().ui.mode, mode); + } +} + +#[test] +#[ignore] +fn toolbar_frame_timing() { + for width in [1600.0, 1000.0, 400.0] { + let mut harness = toolbar_harness(width, Tool::Path); + harness.run_steps(100); + let mut timings = [0.0_f64; 5]; + for timing in &mut timings { + let start = std::time::Instant::now(); + harness.run_steps(1000); + *timing = start.elapsed().as_secs_f64() * 1000.0; + } + timings.sort_by(f64::total_cmp); + eprintln!("Path + lazy mouse, width {width}: {:.2} us/frame median, batches {timings:?}", timings[2]); + } +} + +#[test] +#[ignore] +fn toolbar_window_snapshots() { + let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { + return; + }; + + std::fs::create_dir_all(&directory).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().session.tool.tool = Tool::Path; + harness.state_mut().session.tool.brush.lazy = 20.0; + for (width, scale) in [(1600.0, 1.0), (960.0, 1.0), (960.0, 1.5)] { + harness.set_size(egui::vec2(width, 960.0)); + harness.state_mut().ui.prefs.ui_scale = scale; + harness.run_steps(6); + harness.render().unwrap().save(directory.join(format!("toolbar-{width}-{scale}.png"))).unwrap(); + } +} From 97880c7f05ef86e07e62a1c42106511b4bd25958 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 4 Nov 2026 21:22:46 -0500 Subject: [PATCH 04/73] Derive standard control sizes from the active theme Use theme control heights for toolbar, path, asset, property, bake and browser export controls. Keep width calculations in sync with the rendered controls and verify narrow toolbars at three theme sizes. --- .../ui-egui/src/bake_mode/common_settings.rs | 22 ++++++--- crates/ui-egui/src/dock.rs | 40 ++++++++------- crates/ui-egui/src/shelf.rs | 15 ++++-- crates/ui-egui/src/toolbar.rs | 49 +++++++++++-------- crates/ui-egui/src/windows.rs | 15 +++--- crates/ui-egui/tests/toolbar.rs | 39 ++++++++++----- 6 files changed, 110 insertions(+), 70 deletions(-) diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index d96fdc85..7680903b 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -9,6 +9,8 @@ use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; +const FILE_BUTTON_SIZE: f32 = 20.0; + pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { ui.push_id("common", |ui| { let is_enabled = settings.common.is_enabled; @@ -104,7 +106,8 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { ui.label(tr("Output Size")); ui.horizontal(|ui| { - let dropdown_width = ((ui.available_width() - 24.0 - ui.spacing().item_spacing.x * 2.0) / 2.0).max(40.0); + let button_size = ui.spacing().interact_size.y; + let dropdown_width = ((ui.available_width() - button_size - ui.spacing().item_spacing.x * 2.0) / 2.0).max(40.0); let resolution = |ui: &mut Ui, id: &str, value: &mut BakeResolution| { egui::ComboBox::from_id_salt(id).width(dropdown_width).selected_text(value.pixels().to_string()).show_ui(ui, |ui| { for resolution in BakeResolution::ALL { @@ -112,6 +115,7 @@ fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { } }); }; + resolution(ui, "output_width", &mut settings.resolution); let locked = settings.resolution_height.is_none(); let mut height = settings.resolution_height.unwrap_or(settings.resolution); @@ -119,7 +123,8 @@ fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { if !locked { settings.resolution_height = Some(height); } - if icon_button(ui, if locked { icon::LOCK_SIMPLE } else { icon::LOCK_SIMPLE_OPEN }, tr("Lock Output Size"), locked, 24.0).clicked() { + + if icon_button(ui, if locked { icon::LOCK_SIMPLE } else { icon::LOCK_SIMPLE_OPEN }, tr("Lock Output Size"), locked, button_size).clicked() { settings.resolution_height = if locked { Some(settings.resolution) } else { None }; } }); @@ -131,12 +136,14 @@ fn high_poly_files(app: &mut TextureCraftApp, ui: &mut Ui) { let mut remove = None; for (index, name) in meshes.iter().enumerate() { ui.horizontal(|ui| { - ui.add_sized([ui.available_width() - 24.0, 24.0], egui::Label::new(name).truncate()).on_hover_text(name); - if icon_button(ui, icon::TRASH, tr("Remove"), false, 20.0).clicked() { + let label_width = (ui.available_width() - FILE_BUTTON_SIZE - ui.spacing().item_spacing.x).max(0.0); + ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(name).truncate()).on_hover_text(name); + if icon_button(ui, icon::TRASH, tr("Remove"), false, FILE_BUTTON_SIZE).clicked() { remove = Some(index); } }); } + if meshes.is_empty() { hint(ui, tr("No High-Poly Meshes")); } @@ -152,11 +159,12 @@ fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(tr("Cage Scene")); let cage = app.session.bake_meshes.cage.as_ref().map(|mesh| mesh.name.clone()); ui.horizontal(|ui| { - ui.add_sized([ui.available_width() - 52.0, 24.0], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); - if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, 20.0).clicked() { + let label_width = (ui.available_width() - 2.0 * (FILE_BUTTON_SIZE + ui.spacing().item_spacing.x)).max(0.0); + ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); + if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, FILE_BUTTON_SIZE).clicked() { crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true); } - if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, 20.0).clicked() { + if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, FILE_BUTTON_SIZE).clicked() { app.run("bake.cage.clear", json!({})); } }); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 3a74a80b..4d5a1d06 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -990,38 +990,43 @@ fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { } fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - // Brush preview: a stroke and a sphere with the tool's material. + let tokens = Tokens::get(ui.ctx()); + // Brush preview: a stroke and a sphere with the tool's material let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 88.0), Sense::hover()); - let p = ui.painter(); - p.rect_filled(rect, 2.0, tk.viewport); - let half = rect.width() * 0.5; - let b = &app.session.tool.brush; - let mut pts = Vec::new(); - for k in 0..=40 { - let t = k as f32 / 40.0; - pts.push(pos2(rect.left() + 14.0 + t * (half - 28.0), rect.center().y + (t * 9.0).sin() * 18.0)); + let painter = ui.painter(); + painter.rect_filled(rect, 2.0, tokens.viewport); + let half_width = rect.width() * 0.5; + let brush = &app.session.tool.brush; + let mut points = Vec::new(); + for step in 0..=40 { + let fraction = step as f32 / 40.0; + points.push(pos2(rect.left() + 14.0 + fraction * (half_width - 28.0), rect.center().y + (fraction * 9.0).sin() * 18.0)); } - let w = (b.size / 0.25 * 60.0).clamp(2.0, 30.0); - let a = (b.flow * b.opacity * 255.0) as u8; - p.add(egui::Shape::line(pts, Stroke::new(w, Color32::from_white_alpha(a.max(30))))); - let base = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([0.8; 3]); - crate::thumbs::paint_sphere(p, pos2(rect.left() + half * 1.5, rect.center().y), 36.0, base); + + let stroke_width = (brush.size / 0.25 * 60.0).clamp(2.0, 30.0); + let alpha = (brush.flow * brush.opacity * 255.0) as u8; + painter.add(egui::Shape::line(points, Stroke::new(stroke_width, Color32::from_white_alpha(alpha.max(30))))); + let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([0.8; 3]); + crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), 36.0, base_color); ui.add_space(4.0); + ui.horizontal(|ui| { + let button_size = ui.spacing().interact_size.y; for (tab, icon, tip) in [(PropsTab::Brush, ic::PAINT_BRUSH, tr("Brush")), (PropsTab::Alpha, ic::CIRCLE_HALF, tr("Alpha")), (PropsTab::Material, ic::SPHERE, tr("Material"))] { - if icon_button(ui, icon, tip, app.ui.props_tab == tab, 24.0).clicked() { + if icon_button(ui, icon, tip, app.ui.props_tab == tab, button_size).clicked() { app.ui.props_tab = tab; } } }); ui.separator(); + if app.session.quick_mask.editing { - ui.label(RichText::new(tr("Editing the quick mask: strokes paint where painting is allowed. Press U to finish.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Editing the quick mask: strokes paint where painting is allowed. Press U to finish.")).color(tokens.text_dim)); ui.separator(); } + let tool_section: Option = match app.session.tool.tool { Tool::Projection => Some(stencil_section), Tool::Clone => Some(clone_section), @@ -1034,6 +1039,7 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { section(app, ui); ui.separator(); } + match app.ui.props_tab { PropsTab::Brush => brush_section(app, ui), PropsTab::Alpha => alpha_section(app, ui), diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index f2aaeb65..351219b9 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -156,34 +156,39 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response } } -/// The Assets panel body (a dock tab). +/// The Assets panel body (a dock tab) pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); let mut tab = app.ui.shelf_tab.min(TABS.len() - 1); let searching = !app.ui.shelf_filter.is_empty(); + ui.horizontal_wrapped(|ui| { + let button_size = ui.spacing().interact_size.y; ui.spacing_mut().item_spacing = vec2(2.0, 2.0); for (i, (_, icon, label)) in TABS.iter().enumerate() { - if icon_button(ui, icon, tr(label), i == tab && !searching, 24.0).clicked() { + if icon_button(ui, icon, tr(label), i == tab && !searching, button_size).clicked() { tab = i; app.ui.shelf_filter.clear(); } } }); app.ui.shelf_tab = tab; + ui.horizontal(|ui| { - ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tk.text_dim)); + ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tokens.text_dim)); ui.add(egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search all assets")).desired_width(f32::INFINITY)); }); ui.add_space(4.0); + let filter = app.ui.shelf_filter.to_lowercase(); egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { - // Searching shows matches from every tab, each under its tab's name. + // Searching shows matches from every tab, each under its tab's name for (i, (t, _, title)) in TABS.iter().enumerate() { if filter.is_empty() && i != tab { continue; } + let title = tr(title); match t { Tab::Materials => materials(app, ui, &ctx, &filter, false, title), diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index a075840d..b2e4d83e 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -13,7 +13,6 @@ use crate::state::{Mode, ViewLayout}; use crate::theme::{GUTTER, Tokens, card}; use crate::widgets::{bar_slider, icon_button, icon_button_without_tooltip}; -const BAR_BUTTON_SIZE: f32 = 24.0; const BAR_SPACING: f32 = 10.0; const COMPACT_BAR_SPACING: f32 = 4.0; const BAR_SEPARATOR_WIDTH: f32 = 6.0; @@ -38,11 +37,13 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { egui::Panel::top("paint_bar").exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, egui::Margin::symmetric(8, 0), |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mode_width = 3.0 * BAR_BUTTON_SIZE + 2.0 * BAR_SPACING; + let button_size = ui.spacing().interact_size.y; + let mode_width = 3.0 * button_size + 2.0 * BAR_SPACING; let separator_width = BAR_SEPARATOR_WIDTH + 2.0 * BAR_SPACING; // Leave room for both scroll arrows and at least one button of content - let minimum_strip_width = 3.0 * BAR_BUTTON_SIZE + 2.0 * BAR_SPACING; - let scroll_views = ui.available_width() < mode_width + view_buttons_width(BAR_SPACING) + 2.0 * separator_width + minimum_strip_width; + let minimum_strip_width = 3.0 * button_size + 2.0 * BAR_SPACING; + let scroll_views = + ui.available_width() < mode_width + view_buttons_width(button_size, BAR_SPACING) + 2.0 * separator_width + minimum_strip_width; ui.spacing_mut().item_spacing.x = if scroll_views { COMPACT_BAR_SPACING } else { BAR_SPACING }; mode_buttons(app, ui); @@ -64,14 +65,15 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { }); } -fn view_buttons_width(spacing: f32) -> f32 { +fn view_buttons_width(button_size: f32, spacing: f32) -> f32 { // Five icons, two separators and the six gaps between them - 5.0 * BAR_BUTTON_SIZE + 2.0 * BAR_SEPARATOR_WIDTH + 6.0 * spacing + 5.0 * button_size + 2.0 * BAR_SEPARATOR_WIDTH + 6.0 * spacing } /// View buttons in a right-to-left layout, with the screenshot button at the end fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { - if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, BAR_BUTTON_SIZE).clicked() { + let button_size = ui.spacing().interact_size.y; + if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, button_size).clicked() { app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); } @@ -81,14 +83,14 @@ fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { (ViewLayout::Only3D, ic::CUBE, "3D view only", "ui.layout.3d"), (ViewLayout::Split, ic::COLUMNS, "3D/2D views", "ui.layout.split"), ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, tr(label), command), app.ui.layout == layout, BAR_BUTTON_SIZE).clicked() { + if icon_button(ui, icon, &tip(&app.ui.keymap, tr(label), command), app.ui.layout == layout, button_size).clicked() { crate::menus::invoke(app, &ui.ctx().clone(), command); } } ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; - if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, BAR_BUTTON_SIZE).clicked() { + if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, button_size).clicked() { let mode = if checker { "material" } else { "uvChecker" }; app.run("viewport.view", json!({"mode": mode})); } @@ -96,6 +98,7 @@ fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { /// Scroll tool controls and, in narrow viewports, the view buttons fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, scroll_views: bool) { + let button_size = ui.spacing().interact_size.y; let strip_width = ui.available_width(); let overflow_id = egui::Id::unique("tool_controls_overflow"); let overflowing = ui.data(|data| data.get_temp::(overflow_id)).unwrap_or(false); @@ -103,12 +106,12 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: // A positive delta moves the content right, revealing its start let arrow_scroll_step = strip_width / 2.0; let mut scroll_delta = 0.0; - if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_LEFT, "Scroll left", false, BAR_BUTTON_SIZE).clicked() { + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_LEFT, "Scroll left", false, button_size).clicked() { scroll_delta = arrow_scroll_step; } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_RIGHT, "Scroll right", false, BAR_BUTTON_SIZE).clicked() { + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_RIGHT, "Scroll right", false, button_size).clicked() { scroll_delta = -arrow_scroll_step; } @@ -123,7 +126,7 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: tool_controls(app, ui, tokens); if scroll_views { ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); - let size = vec2(view_buttons_width(ui.spacing().item_spacing.x), ui.available_height()); + let size = vec2(view_buttons_width(button_size, ui.spacing().item_spacing.x), ui.available_height()); ui.allocate_ui_with_layout(size, egui::Layout::right_to_left(egui::Align::Center), |ui| view_buttons(app, ui)); } }); @@ -147,6 +150,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) const DEFAULT_LAZY_DISTANCE_PX: f32 = 20.0; const TOOL_ICON_SIZE: f32 = 15.0; + let button_size = ui.spacing().interact_size.y; let tool = app.session.tool.tool; ui.label(RichText::new(tool_icon(tool)).size(TOOL_ICON_SIZE).color(tokens.text_strong)).on_hover_text(tr(tool.label())); @@ -175,7 +179,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) ui.separator(); let lazy_on = brush.lazy > 0.0; - if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, 24.0).clicked() { + if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, button_size).clicked() { brush.lazy = if lazy_on { 0.0 } else { DEFAULT_LAZY_DISTANCE_PX }; } if lazy_on { @@ -186,13 +190,13 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) } ui.separator(); - if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), brush.symmetry.x, 24.0).clicked() { + if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), brush.symmetry.x, button_size).clicked() { brush.symmetry.x = !brush.symmetry.x; } - if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), brush.symmetry.y, 24.0).clicked() { + if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), brush.symmetry.y, button_size).clicked() { brush.symmetry.y = !brush.symmetry.y; } - if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, 24.0).clicked() { + if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, button_size).clicked() { brush.particles.enabled = !brush.particles.enabled; } @@ -222,7 +226,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) (FillMode::UvIsland, ic::SHAPES, tr("UV island fill")), (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), ] { - if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, 24.0).clicked() { + if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, button_size).clicked() { app.session.tool.fill_mode = fill_mode; } } @@ -238,27 +242,30 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) /// Bake, Painting and Rendering mode buttons for a right-to-left layout, so Rendering is added first fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let button_size = ui.spacing().interact_size.y; for (mode, icon, label, command) in [ (Mode::Rendering, ic::APERTURE, tr("Rendering (path traced)"), "ui.mode.render"), (Mode::Painting, ic::PALETTE, tr("Painting"), "ui.mode.paint"), (Mode::Baking, ic::ATOM, tr("Bake Mesh Maps"), "ui.mode.bake"), ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, BAR_BUTTON_SIZE).clicked() { + if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, button_size).clicked() { crate::menus::invoke(app, &ui.ctx().clone(), command); } } } -/// Path tool options and actions (top bar and properties). +/// Path tool options and actions (top bar and properties) pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let button_size = ui.spacing().interact_size.y; let path = &mut app.session.tool.path; - if icon_button(ui, ic::POLYGON, tr("Closed path"), path.closed, 24.0).clicked() { + if icon_button(ui, ic::POLYGON, tr("Closed path"), path.closed, button_size).clicked() { path.closed = !path.closed; } let fill_tip = if path.closed { tr("Fill the closed path (lasso)") } else { tr("Fill the path (close it first)") }; - if icon_button(ui, ic::PAINT_BUCKET, fill_tip, path.fill, 24.0).clicked() { + if icon_button(ui, ic::PAINT_BUCKET, fill_tip, path.fill, button_size).clicked() { path.fill = !path.fill; } + let has_points = !path.points.is_empty(); if ui .add_enabled(has_points, egui::Button::new(format!("{} {}", ic::CHECK, tr("Apply")))) diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index c8bd72c5..3672ad45 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -615,8 +615,7 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.windows.settings = open; } -/// Browser File › Export Mesh: pick the download format (the desktop picks it in the save -/// dialog). +/// Browser File › Export Mesh: pick the download format #[cfg(target_arch = "wasm32")] fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) { let formats = [ @@ -627,18 +626,20 @@ fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.export_mesh { return; } + let mut open = true; let mut picked = None; dialog("export_mesh", tr("Export mesh"), &mut open).show(ctx, |ui| { ui.label(caption(tr("Download as"))); - for (ext, label, hint) in formats { - if ui.add_sized(vec2(220.0, 24.0), egui::Button::new(label)).on_hover_text(hint).clicked() { - picked = Some(ext); + for (extension, label, hint) in formats { + if ui.add_sized(vec2(220.0, ui.spacing().interact_size.y), egui::Button::new(label)).on_hover_text(hint).clicked() { + picked = Some(extension); } } }); - if let Some(ext) = picked { - crate::web_files::export_mesh(app, ext); + + if let Some(extension) = picked { + crate::web_files::export_mesh(app, extension); open = false; } app.ui.windows.export_mesh = open; diff --git a/crates/ui-egui/tests/toolbar.rs b/crates/ui-egui/tests/toolbar.rs index fc5c295a..76b0053d 100644 --- a/crates/ui-egui/tests/toolbar.rs +++ b/crates/ui-egui/tests/toolbar.rs @@ -12,8 +12,13 @@ fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> let mut app = TextureCraftApp::new(&context, session); app.session.tool.tool = tool; app.session.tool.brush.lazy = 20.0; - let mut harness = - Harness::builder().with_size(egui::vec2(width, 200.0)).with_context_setup(theme::install).build_ui_state(|ui, app| toolbar::paint_bar(app, ui), app); + let mut harness = Harness::builder() + .with_size(egui::vec2(width, 200.0)) + .with_context_setup(|context| { + theme::install(context); + theme::apply(context, theme::Brightness::default(), theme::Accent::default()); + }) + .build_ui_state(|ui, app| toolbar::paint_bar(app, ui), app); harness.run_steps(4); harness } @@ -33,17 +38,25 @@ fn size_label(harness: &Harness<'_, TextureCraftApp>) -> (egui::Pos2, egui::Rect #[test] fn narrow_toolbars_keep_scroll_arrows_and_mode_buttons_separate() { let mut harness = toolbar_harness(700.0, Tool::Path); - for width in [500.0, 450.0, 400.0, 350.0, 240.0, 200.0] { - harness.set_size(egui::vec2(width, 200.0)); - harness.run_steps(4); - let left = harness.get_by_label("Scroll left").rect(); - let right = harness.get_by_label("Scroll right").rect(); - let bake = harness.get_by_label("Bake Mesh Maps (F8)").rect(); - let (_, clip) = size_label(&harness); - assert!(left.right() <= right.left(), "arrows overlap at width {width}: {left:?}, {right:?}"); - assert!(right.right() < bake.left(), "scrolling overlaps the mode buttons at width {width}"); - assert!(clip.left() >= left.right() && clip.right() <= right.left(), "content covers an arrow at width {width}: {clip:?}"); - assert!(harness.ctx.content_rect().contains_rect(left) && harness.ctx.content_rect().contains_rect(bake)); + for button_size in [20.0, 24.0, 28.0] { + harness.ctx.all_styles_mut(|style| style.spacing.interact_size = egui::Vec2::splat(button_size)); + for width in [500.0, 450.0, 400.0, 350.0, 240.0, 200.0] { + let width = width * button_size / 24.0; + harness.set_size(egui::vec2(width, 200.0)); + harness.run_steps(4); + let left = harness.get_by_label("Scroll left").rect(); + let right = harness.get_by_label("Scroll right").rect(); + let bake = harness.get_by_label("Bake Mesh Maps (F8)").rect(); + let (_, clip) = size_label(&harness); + for button in [left, right, bake] { + assert_eq!(button.size(), egui::Vec2::splat(button_size)); + } + + assert!(left.right() <= right.left(), "arrows overlap at width {width}: {left:?}, {right:?}"); + assert!(right.right() < bake.left(), "scrolling overlaps the mode buttons at width {width}"); + assert!(clip.left() >= left.right() && clip.right() <= right.left(), "content covers an arrow at width {width}: {clip:?}"); + assert!(harness.ctx.content_rect().contains_rect(left) && harness.ctx.content_rect().contains_rect(bake)); + } } } From 6b31b9e376b519c18fabad32efec2cbc98d26b8b Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 4 Nov 2026 21:49:36 -0500 Subject: [PATCH 05/73] Derive bake file button sizes from the active UI Use the UI control height for high-poly and cage file buttons and their row-width reservations. Cover smaller and larger control sizes in the bake UI regression test. --- crates/ui-egui/src/bake_mode/common_settings.rs | 14 +++++++------- crates/ui-egui/tests/bake_mode.rs | 10 ++++++++++ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index 7680903b..d6710290 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -9,8 +9,6 @@ use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; -const FILE_BUTTON_SIZE: f32 = 20.0; - pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { ui.push_id("common", |ui| { let is_enabled = settings.common.is_enabled; @@ -136,9 +134,10 @@ fn high_poly_files(app: &mut TextureCraftApp, ui: &mut Ui) { let mut remove = None; for (index, name) in meshes.iter().enumerate() { ui.horizontal(|ui| { - let label_width = (ui.available_width() - FILE_BUTTON_SIZE - ui.spacing().item_spacing.x).max(0.0); + let button_size = ui.spacing().interact_size.y; + let label_width = (ui.available_width() - button_size - ui.spacing().item_spacing.x).max(0.0); ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(name).truncate()).on_hover_text(name); - if icon_button(ui, icon::TRASH, tr("Remove"), false, FILE_BUTTON_SIZE).clicked() { + if icon_button(ui, icon::TRASH, tr("Remove"), false, button_size).clicked() { remove = Some(index); } }); @@ -159,12 +158,13 @@ fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(tr("Cage Scene")); let cage = app.session.bake_meshes.cage.as_ref().map(|mesh| mesh.name.clone()); ui.horizontal(|ui| { - let label_width = (ui.available_width() - 2.0 * (FILE_BUTTON_SIZE + ui.spacing().item_spacing.x)).max(0.0); + let button_size = ui.spacing().interact_size.y; + let label_width = (ui.available_width() - 2.0 * (button_size + ui.spacing().item_spacing.x)).max(0.0); ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); - if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, FILE_BUTTON_SIZE).clicked() { + if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, button_size).clicked() { crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true); } - if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, FILE_BUTTON_SIZE).clicked() { + if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, button_size).clicked() { app.run("bake.cage.clear", json!({})); } }); diff --git a/crates/ui-egui/tests/bake_mode.rs b/crates/ui-egui/tests/bake_mode.rs index 409966c6..acd1135c 100644 --- a/crates/ui-egui/tests/bake_mode.rs +++ b/crates/ui-egui/tests/bake_mode.rs @@ -106,14 +106,24 @@ fn cage_and_skew_controls_require_a_high_poly_and_follow_cage_type() { harness.run_steps(3); assert!(harness.query_by_label("Cage Type").is_none()); assert!(harness.query_by_label("Skew Correction").is_none()); + harness.state_mut().session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); harness.run_steps(3); harness.get_by_label("Max Frontal Distance"); harness.get_by_label("Skew Correction"); + click(&mut harness, "Cage Type"); click(&mut harness, "Custom File"); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.cage.kind, CageType::CustomFile); harness.get_by_label("Cage Scene"); assert!(harness.query_by_label("Max Frontal Distance").is_none()); assert!(harness.query_by_label("Skew Correction").is_none()); + + for button_size in [20.0, 28.0] { + harness.ctx.all_styles_mut(|style| style.spacing.interact_size = egui::Vec2::splat(button_size)); + harness.run_steps(3); + for label in ["Remove", "Load Cage"] { + assert_eq!(harness.get_by_label(label).rect().size(), egui::Vec2::splat(button_size)); + } + } } From e26f196888dcc181fccfe3b45808c13bdb1f4097 Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:17:34 +0400 Subject: [PATCH 06/73] Camera bookmarks: Ctrl+1..9 shortcuts, smooth glide in the UI, docs Saved cameras (Project.cameras) already act as bookmarks; add camera.bookmark1..9 commands, a short viewport glide when going to a camera from the UI, a test and a control-protocol section. --- crates/engine/src/camera_cmds.rs | 36 ++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 48 +++++++++++++++++++++++++++++++- docs/control-protocol.md | 9 ++++++ 3 files changed, 92 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/camera_cmds.rs b/crates/engine/src/camera_cmds.rs index af94815c..9c44c06e 100644 --- a/crates/engine/src/camera_cmds.rs +++ b/crates/engine/src/camera_cmds.rs @@ -28,6 +28,15 @@ pub fn specs() -> Vec { ), cmd!("camera.remove", "Remove camera", [], None, "{index? | name?}", has_cameras, remove), cmd!("camera.rename", "Rename camera", [], None, "{index? | name?, to}", has_cameras, rename), + cmd!("camera.bookmark1", "Go to camera 1", ["Viewport"], Some("Ctrl+1"), "{}", always, |s, _| bookmark(s, 0)), + cmd!("camera.bookmark2", "Go to camera 2", ["Viewport"], Some("Ctrl+2"), "{}", always, |s, _| bookmark(s, 1)), + cmd!("camera.bookmark3", "Go to camera 3", ["Viewport"], Some("Ctrl+3"), "{}", always, |s, _| bookmark(s, 2)), + cmd!("camera.bookmark4", "Go to camera 4", ["Viewport"], Some("Ctrl+4"), "{}", always, |s, _| bookmark(s, 3)), + cmd!("camera.bookmark5", "Go to camera 5", ["Viewport"], Some("Ctrl+5"), "{}", always, |s, _| bookmark(s, 4)), + cmd!("camera.bookmark6", "Go to camera 6", ["Viewport"], Some("Ctrl+6"), "{}", always, |s, _| bookmark(s, 5)), + cmd!("camera.bookmark7", "Go to camera 7", ["Viewport"], Some("Ctrl+7"), "{}", always, |s, _| bookmark(s, 6)), + cmd!("camera.bookmark8", "Go to camera 8", ["Viewport"], Some("Ctrl+8"), "{}", always, |s, _| bookmark(s, 7)), + cmd!("camera.bookmark9", "Go to camera 9", ["Viewport"], Some("Ctrl+9"), "{}", always, |s, _| bookmark(s, 8)), cmd!("viewport.focusAt", "Focus depth of field here", [], None, "{x, y (viewport pixels), viewport?: [w, h]}", always, focus_at), ] } @@ -132,6 +141,14 @@ fn select(s: &mut Session, p: &Value) -> Result { Ok(crate::view_cmds::camera_json(s)) } +/// Shortcut slot `slot` (0-based): the n-th saved camera, in list order. +fn bookmark(s: &mut Session, slot: usize) -> Result { + if slot >= s.doc.project.cameras.len() { + return Err(bad("camera.bookmark", "no saved camera in that slot (see camera.list)")); + } + select(s, &json!({ "index": slot })) +} + fn remove(s: &mut Session, p: &Value) -> Result { let i = which(s, "camera.remove", p)?; s.edit("Remove camera", |s| { @@ -202,6 +219,25 @@ mod tests { assert_eq!(s.doc.project.cameras.len(), 2, "removing is undoable"); } + #[test] + fn number_shortcuts_go_to_the_first_nine_cameras() { + let mut s = session(); + assert!(execute(&mut s, "camera.bookmark1", &Value::Null).is_err(), "no cameras yet"); + execute(&mut s, "camera.set", &json!({"yaw": 30})).unwrap(); + let first = s.camera; + execute(&mut s, "camera.add", &json!({"name": "A"})).unwrap(); + execute(&mut s, "camera.orbit", &json!({"dx": 50})).unwrap(); + execute(&mut s, "camera.add", &json!({"name": "B"})).unwrap(); + execute(&mut s, "camera.bookmark1", &Value::Null).unwrap(); + assert_eq!(s.camera, first); + execute(&mut s, "camera.bookmark2", &Value::Null).unwrap(); + assert_eq!(execute(&mut s, "camera.list", &Value::Null).unwrap()["current"], 1); + assert!(execute(&mut s, "camera.bookmark3", &Value::Null).is_err(), "empty slot"); + let ids: Vec<_> = crate::command_specs().iter().filter(|c| c.id.starts_with("camera.bookmark")).collect(); + assert_eq!(ids.len(), 9); + assert!(ids.iter().all(|c| c.shortcut.is_some())); + } + #[test] fn cameras_round_trip_through_the_project_file() { let mut s = session(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8bfc66c9..c6112eb3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -75,6 +75,8 @@ pub struct Toast { pub struct TextureCraftApp { pub session: Session, + /// A smooth move to a saved camera in progress. + camera_glide: Option, pub ui: UiState, pub gpu: Option, pub control: Option>, @@ -135,6 +137,7 @@ impl TextureCraftApp { }); let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0; let mut app = TextureCraftApp { + camera_glide: None, session, ui, gpu, @@ -183,8 +186,16 @@ impl TextureCraftApp { /// Run an engine command, reporting errors as toasts. Returns the result on success. pub fn run(&mut self, id: &str, params: Value) -> Option { + // Going to a saved camera glides there; the control channel and CLI jump straight away. + let glide_from = (id.starts_with("camera.select") || id.starts_with("camera.bookmark")).then_some(self.session.camera); match texturecraft_engine::execute(&mut self.session, id, ¶ms) { - Ok(v) => Some(v), + Ok(v) => { + if let Some(from) = glide_from.filter(|f| *f != self.session.camera) { + self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time }); + self.session.camera = from; + } + Some(v) + } Err(e) => { self.toast(e.to_string(), true); None @@ -418,6 +429,40 @@ impl TextureCraftApp { } } +/// A smooth move of the viewport camera (see [`TextureCraftApp::run`]). +struct CameraGlide { + from: texturecraft_engine::geom::OrbitCamera, + to: texturecraft_engine::geom::OrbitCamera, + start: f64, +} + +const GLIDE_SECONDS: f64 = 0.35; + +impl TextureCraftApp { + /// Advance the camera glide by one frame. + fn step_camera_glide(&mut self, ctx: &egui::Context) { + let Some(g) = &self.camera_glide else { return }; + let t = ((self.last_time - g.start) / GLIDE_SECONDS).clamp(0.0, 1.0) as f32; + let e = t * t * (3.0 - 2.0 * t); + let (a, b) = (g.from, g.to); + let mix = |x: f32, y: f32| x + (y - x) * e; + let mut c = b; + c.target = a.target.lerp(b.target, e); + c.yaw = mix(a.yaw, b.yaw); + c.pitch = mix(a.pitch, b.pitch); + c.distance = mix(a.distance, b.distance); + c.fov = mix(a.fov, b.fov); + // Orthographic switches at the end (the projections cannot be blended). + c.ortho = if t >= 1.0 { b.ortho } else { a.ortho }; + self.session.camera = c; + self.session.revision = self.session.revision.wrapping_add(1); + if t >= 1.0 { + self.camera_glide = None; + } + ctx.request_repaint(); + } +} + impl eframe::App for TextureCraftApp { /// The browser never tells eframe the page is closing, so save often there. fn auto_save_interval(&self) -> std::time::Duration { @@ -442,6 +487,7 @@ impl eframe::App for TextureCraftApp { theme::apply(ctx, style.0, style.1); self.styled = Some(style); } + self.step_camera_glide(ctx); control::poll(self, ctx); web_files::poll(self); let dropped = ctx.input(|i| i.raw.dropped_files.clone()); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3d7c2206..74322c74 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -223,6 +223,15 @@ printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","para '{"id":2,"method":"render","params":{"width":512,"height":512}}' | texturecraft-cli serve ``` +## Camera bookmarks + +Saved cameras (`Project.cameras`, stored in the `.tcraft` file) are the camera bookmarks. +`camera.add {name?}` saves the current view, `camera.list` lists them (`current` is the one the view +is at), `camera.select {index? | name?}` restores one, `camera.rename {index? | name?, to}` and +`camera.remove {index? | name?}` edit them. `camera.bookmark1` … `camera.bookmark9` (Ctrl+1 … Ctrl+9) +go to the first nine. Commands jump straight to the view; the desktop UI glides there over about a third +of a second. + ## MaterialCraft materials A `.mcmat` portable material (MaterialCraft's format, read here by `formats::mcmat`; the manifest is From 3f3bf357f3c107b4ac7fa4ce093ad4d4d0088848 Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:42:54 +0400 Subject: [PATCH 07/73] Camera bookmarks: translate the Go to camera commands --- crates/ui-egui/src/i18n/ar.rs | 9 +++++++++ crates/ui-egui/src/i18n/de.rs | 9 +++++++++ crates/ui-egui/src/i18n/es.rs | 9 +++++++++ crates/ui-egui/src/i18n/fr.rs | 9 +++++++++ crates/ui-egui/src/i18n/it.rs | 9 +++++++++ crates/ui-egui/src/i18n/ja.rs | 9 +++++++++ crates/ui-egui/src/i18n/ko.rs | 9 +++++++++ crates/ui-egui/src/i18n/pt_br.rs | 9 +++++++++ crates/ui-egui/src/i18n/zh_hans.rs | 9 +++++++++ 9 files changed, 81 insertions(+) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 6ef517e9..543ce315 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -143,6 +143,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "مدمج: {mesh}"), ("Cage: {name}", "القفص (Cage): {name}"), ("Camera", "الكاميرا"), + ("Go to camera 1", "الانتقال إلى الكاميرا 1"), + ("Go to camera 2", "الانتقال إلى الكاميرا 2"), + ("Go to camera 3", "الانتقال إلى الكاميرا 3"), + ("Go to camera 4", "الانتقال إلى الكاميرا 4"), + ("Go to camera 5", "الانتقال إلى الكاميرا 5"), + ("Go to camera 6", "الانتقال إلى الكاميرا 6"), + ("Go to camera 7", "الانتقال إلى الكاميرا 7"), + ("Go to camera 8", "الانتقال إلى الكاميرا 8"), + ("Go to camera 9", "الانتقال إلى الكاميرا 9"), ("Camera settings", "إعدادات الكاميرا"), ("Cancel", "إلغاء"), ("Cancel the stroke", "إلغاء ضربة الفرشاة"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index caaabb14..ff21513c 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -143,6 +143,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integriert: {mesh}"), ("Cage: {name}", "Cage: {name}"), ("Camera", "Kamera"), + ("Go to camera 1", "Zu Kamera 1 wechseln"), + ("Go to camera 2", "Zu Kamera 2 wechseln"), + ("Go to camera 3", "Zu Kamera 3 wechseln"), + ("Go to camera 4", "Zu Kamera 4 wechseln"), + ("Go to camera 5", "Zu Kamera 5 wechseln"), + ("Go to camera 6", "Zu Kamera 6 wechseln"), + ("Go to camera 7", "Zu Kamera 7 wechseln"), + ("Go to camera 8", "Zu Kamera 8 wechseln"), + ("Go to camera 9", "Zu Kamera 9 wechseln"), ("Camera settings", "Kameraeinstellungen"), ("Cancel", "Abbrechen"), ("Cancel the stroke", "Strich abbrechen"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 6c8ccccb..512953cc 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -143,6 +143,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integrada: {mesh}"), ("Cage: {name}", "Jaula: {name}"), ("Camera", "Cámara"), + ("Go to camera 1", "Ir a la cámara 1"), + ("Go to camera 2", "Ir a la cámara 2"), + ("Go to camera 3", "Ir a la cámara 3"), + ("Go to camera 4", "Ir a la cámara 4"), + ("Go to camera 5", "Ir a la cámara 5"), + ("Go to camera 6", "Ir a la cámara 6"), + ("Go to camera 7", "Ir a la cámara 7"), + ("Go to camera 8", "Ir a la cámara 8"), + ("Go to camera 9", "Ir a la cámara 9"), ("Camera settings", "Ajustes de cámara"), ("Cancel", "Cancelar"), ("Cancel the stroke", "Cancelar el trazo"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f10bba8d..9921d701 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -149,6 +149,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Intégré : {mesh}"), ("Cage: {name}", "Cage : {name}"), ("Camera", "Caméra"), + ("Go to camera 1", "Aller à la caméra 1"), + ("Go to camera 2", "Aller à la caméra 2"), + ("Go to camera 3", "Aller à la caméra 3"), + ("Go to camera 4", "Aller à la caméra 4"), + ("Go to camera 5", "Aller à la caméra 5"), + ("Go to camera 6", "Aller à la caméra 6"), + ("Go to camera 7", "Aller à la caméra 7"), + ("Go to camera 8", "Aller à la caméra 8"), + ("Go to camera 9", "Aller à la caméra 9"), ("Camera settings", "Paramètres de la caméra"), ("Cancel", "Annuler"), ("Cancel the stroke", "Annuler le trait"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1c19d597..0516b8ac 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -146,6 +146,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integrata: {mesh}"), ("Cage: {name}", "Gabbia: {name}"), ("Camera", "Camera"), + ("Go to camera 1", "Vai alla camera 1"), + ("Go to camera 2", "Vai alla camera 2"), + ("Go to camera 3", "Vai alla camera 3"), + ("Go to camera 4", "Vai alla camera 4"), + ("Go to camera 5", "Vai alla camera 5"), + ("Go to camera 6", "Vai alla camera 6"), + ("Go to camera 7", "Vai alla camera 7"), + ("Go to camera 8", "Vai alla camera 8"), + ("Go to camera 9", "Vai alla camera 9"), ("Camera settings", "Impostazioni camera"), ("Cancel", "Annulla"), ("Cancel the stroke", "Annulla il tratto"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 068603b5..09e69594 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -149,6 +149,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "組み込み: {mesh}"), ("Cage: {name}", "ケージ: {name}"), ("Camera", "カメラ"), + ("Go to camera 1", "カメラ 1 に移動"), + ("Go to camera 2", "カメラ 2 に移動"), + ("Go to camera 3", "カメラ 3 に移動"), + ("Go to camera 4", "カメラ 4 に移動"), + ("Go to camera 5", "カメラ 5 に移動"), + ("Go to camera 6", "カメラ 6 に移動"), + ("Go to camera 7", "カメラ 7 に移動"), + ("Go to camera 8", "カメラ 8 に移動"), + ("Go to camera 9", "カメラ 9 に移動"), ("Camera settings", "カメラ設定"), ("Cancel", "キャンセル"), ("Cancel the stroke", "ストロークをキャンセル"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 137d6177..165a8584 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -143,6 +143,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "기본 제공: {mesh}"), ("Cage: {name}", "케이지: {name}"), ("Camera", "카메라"), + ("Go to camera 1", "카메라 1 보기"), + ("Go to camera 2", "카메라 2 보기"), + ("Go to camera 3", "카메라 3 보기"), + ("Go to camera 4", "카메라 4 보기"), + ("Go to camera 5", "카메라 5 보기"), + ("Go to camera 6", "카메라 6 보기"), + ("Go to camera 7", "카메라 7 보기"), + ("Go to camera 8", "카메라 8 보기"), + ("Go to camera 9", "카메라 9 보기"), ("Camera settings", "카메라 설정"), ("Cancel", "취소"), ("Cancel the stroke", "스트로크 취소"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 99627b25..1a058da9 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -146,6 +146,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Embutida: {mesh}"), ("Cage: {name}", "Cage: {name}"), ("Camera", "Câmera"), + ("Go to camera 1", "Ir para a câmera 1"), + ("Go to camera 2", "Ir para a câmera 2"), + ("Go to camera 3", "Ir para a câmera 3"), + ("Go to camera 4", "Ir para a câmera 4"), + ("Go to camera 5", "Ir para a câmera 5"), + ("Go to camera 6", "Ir para a câmera 6"), + ("Go to camera 7", "Ir para a câmera 7"), + ("Go to camera 8", "Ir para a câmera 8"), + ("Go to camera 9", "Ir para a câmera 9"), ("Camera settings", "Configurações da câmera"), ("Cancel", "Cancelar"), ("Cancel the stroke", "Cancelar o traço"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 18623ce3..e86ef6ef 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -125,6 +125,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "内置:{mesh}"), ("Cage: {name}", "笼体:{name}"), ("Camera", "相机"), + ("Go to camera 1", "转到相机 1"), + ("Go to camera 2", "转到相机 2"), + ("Go to camera 3", "转到相机 3"), + ("Go to camera 4", "转到相机 4"), + ("Go to camera 5", "转到相机 5"), + ("Go to camera 6", "转到相机 6"), + ("Go to camera 7", "转到相机 7"), + ("Go to camera 8", "转到相机 8"), + ("Go to camera 9", "转到相机 9"), ("Camera settings", "相机设置"), ("Cancel", "取消"), ("Cancel the stroke", "取消笔画"), From d5aaea9331adb9658c9ac61fc996a968742fbc5d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 05:24:31 +0000 Subject: [PATCH 08/73] Bake mode: mesh map bakers list and per-map settings Lay bake mode out as texture sets over a Mesh Map Bakers list, then Common Settings | Mesh Map Settings tabs, with the log under both columns. A row's checkbox enables a map for baking; clicking the row selects it, and Mesh Map Settings shows only the selected map behind a texture set / map breadcrumb with dropdowns. Selecting never changes what bakes. Saved bake docks from before this layout, or that cannot be read, load as the bake layout instead of the painting default. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/bake_mode.rs | 31 +++-- crates/ui-egui/src/bake_mode/breadcrumb.rs | 35 +++++ .../ui-egui/src/bake_mode/common_settings.rs | 13 +- crates/ui-egui/src/bake_mode/controls.rs | 62 +++------ crates/ui-egui/src/bake_mode/map_settings.rs | 40 +++--- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 75 +++++++++++ crates/ui-egui/src/docking.rs | 121 ++++++++++++------ crates/ui-egui/src/i18n/ar.rs | 6 +- crates/ui-egui/src/i18n/de.rs | 6 +- crates/ui-egui/src/i18n/es.rs | 6 +- crates/ui-egui/src/i18n/fr.rs | 6 +- crates/ui-egui/src/i18n/it.rs | 6 +- crates/ui-egui/src/i18n/ja.rs | 6 +- crates/ui-egui/src/i18n/ko.rs | 6 +- crates/ui-egui/src/i18n/pt_br.rs | 6 +- crates/ui-egui/src/i18n/zh_hans.rs | 6 +- crates/ui-egui/src/menus.rs | 5 +- crates/ui-egui/src/state.rs | 95 +++++++++++++- crates/ui-egui/tests/bake_mode.rs | 96 ++++++++++++-- crates/ui-egui/tests/skew_paint.rs | 5 +- crates/ui-egui/tests/ui_snapshots.rs | 20 +-- docs/parity.md | 7 +- 22 files changed, 508 insertions(+), 151 deletions(-) create mode 100644 crates/ui-egui/src/bake_mode/breadcrumb.rs create mode 100644 crates/ui-egui/src/bake_mode/mesh_map_bakers.rs diff --git a/crates/ui-egui/src/bake_mode.rs b/crates/ui-egui/src/bake_mode.rs index c0397a49..a5ee88f4 100644 --- a/crates/ui-egui/src/bake_mode.rs +++ b/crates/ui-egui/src/bake_mode.rs @@ -1,10 +1,12 @@ //! Bake Mode presentation; persisted settings live in core and edits use engine commands mod bake_paint_brush; +mod breadcrumb; mod common_settings; pub use bake_paint_brush::BakePaintBrush; mod controls; mod map_settings; +mod mesh_map_bakers; use egui::{Ui, vec2}; use serde_json::json; @@ -37,19 +39,32 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { }); } -pub fn bake_body(app: &mut TextureCraftApp, ui: &mut Ui) { - edit_settings(app, ui, "bake_maps", |_, ui, settings| { - for map in BakedMap::ALL { - ui.push_id(map, |ui| map_settings::show(ui, map, &mut settings.maps)); - ui.add_space(6.0); - } - }); +/// The Mesh Map Bakers panel: which maps bake and which one Mesh Map Settings shows +pub fn mesh_map_bakers_panel(app: &mut TextureCraftApp, ui: &mut Ui) { + edit_settings(app, ui, "mesh_map_bakers", mesh_map_bakers::show); } -pub fn settings_body(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The Mesh Map Settings panel: the breadcrumb, then the selected map's parameters +pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { + let Some(texture_set) = app.session.doc.project.texture_sets.get(app.session.ts()) else { return }; + + let selected = selected_map(app.ui.selected_baked_map, &texture_set.bake); + breadcrumb::show(app, ui, selected); + ui.separator(); + edit_settings(app, ui, "mesh_map_settings", |_, ui, settings| ui.push_id(selected, |ui| map_settings::show(ui, selected, &mut settings.maps)).inner); +} + +/// The Common Settings panel: output, high poly, cage and skew settings +pub fn common_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { edit_settings(app, ui, "bake_common_settings", common_settings::show); } +/// The map whose settings show: the chosen one, else the first enabled map, else Normal +fn selected_map(selection: Option, settings: &BakeSettings) -> BakedMap { + selection.or_else(|| settings.maps.enabled().next()).unwrap_or(BakedMap::Normal) +} + +/// Draw `contents` over a copy of the active set's bake settings and run `bake.settings` on change fn edit_settings(app: &mut TextureCraftApp, ui: &mut Ui, scroll_id: &str, contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings)) { let set_index = app.session.ts(); let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return }; diff --git a/crates/ui-egui/src/bake_mode/breadcrumb.rs b/crates/ui-egui/src/bake_mode/breadcrumb.rs new file mode 100644 index 00000000..14dc7fd5 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/breadcrumb.rs @@ -0,0 +1,35 @@ +use egui::{RichText, Ui}; +use egui_phosphor::regular as icon; +use serde_json::json; +use texturecraft_engine::core::BakedMap; + +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr}; + +/// The texture set and selected map above Mesh Map Settings, each behind a dropdown to switch it +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, selected: BakedMap) { + let active_set = app.session.ts(); + let set_names: Vec = app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.name.clone()).collect(); + + ui.horizontal(|ui| { + ui.menu_button(icon::CARET_RIGHT, |ui| { + for (set_index, name) in set_names.iter().enumerate() { + if ui.selectable_label(set_index == active_set, name).clicked() { + app.run("textureSet.select", json!({ "ts": set_index })); + ui.close(); + } + } + }); + ui.label(set_names.get(active_set).map_or("", String::as_str)); + + ui.menu_button(icon::CARET_RIGHT, |ui| { + for map in BakedMap::ALL { + if ui.selectable_label(map == selected, tr(baked_map_label(map))).clicked() { + app.ui.selected_baked_map = Some(map); + ui.close(); + } + } + }); + ui.label(RichText::new(tr(baked_map_label(selected))).strong()); + }); +} diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index d96fdc85..7df96827 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -9,10 +9,12 @@ use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; +/// The output and high-poly sections, then cage (needs a high poly) and skew (needs a distance cage) pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { ui.push_id("common", |ui| { + // Restore Defaults keeps whether the texture set is included in the bake let is_enabled = settings.common.is_enabled; - if section(ui, tr("Common Parameters"), None, |ui| { + if section(ui, tr("Common Parameters"), |ui| { output_size(ui, &mut settings.common); choice( ui, @@ -31,9 +33,10 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe settings.common = CommonBakeSettings { is_enabled, ..CommonBakeSettings::default() }; } }); + ui.add_space(8.0); ui.push_id("high_poly", |ui| { - if section(ui, tr("High-Poly Parameters"), None, |ui| { + if section(ui, tr("High-Poly Parameters"), |ui| { ui.checkbox(&mut settings.high_poly.use_low_as_high, tr("Use Low Poly Mesh as High Poly Mesh")); high_poly_files(app, ui); if !app.session.bake_meshes.high.is_empty() { @@ -52,10 +55,11 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe settings.high_poly = Default::default(); } }); + if !app.session.bake_meshes.high.is_empty() { ui.add_space(8.0); ui.push_id("cage", |ui| { - if section(ui, tr("Cage"), None, |ui| { + if section(ui, tr("Cage"), |ui| { choice( ui, tr("Cage Type"), @@ -76,10 +80,11 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe settings.cage = Default::default(); } }); + if settings.cage.kind == CageType::DistanceBased { ui.add_space(8.0); ui.push_id("skew", |ui| { - if section(ui, tr("Skew Correction"), None, |ui| { + if section(ui, tr("Skew Correction"), |ui| { choice( ui, tr("Skew Correction Method"), diff --git a/crates/ui-egui/src/bake_mode/controls.rs b/crates/ui-egui/src/bake_mode/controls.rs index 4c2e6b88..f260bf7c 100644 --- a/crates/ui-egui/src/bake_mode/controls.rs +++ b/crates/ui-egui/src/bake_mode/controls.rs @@ -3,63 +3,35 @@ use crate::theme::{Tokens, caption}; use egui::collapsing_header::CollapsingState; use egui::{RichText, Ui}; -pub(super) fn section_header(ui: &mut Ui, title: &str, mut is_enabled: Option<&mut bool>, collapsing_state: Option<&mut CollapsingState>) -> bool { +/// A section's title bar with its chevron; clicking it opens or closes the section +fn section_header(ui: &mut Ui, title: &str, collapsing_state: &mut CollapsingState) { let tokens = Tokens::get(ui.ctx()); - let text_color = if is_enabled.as_deref().copied().unwrap_or(true) { tokens.text_strong } else { tokens.text_dim }; - let mut checkbox_rect = None; - let mut arrow_rect = None; - let header = egui::Frame::NONE.fill(tokens.row).corner_radius(tokens.cr()).inner_margin(egui::Margin::symmetric(8, 4)).show(ui, |ui| { ui.set_min_width(ui.available_width()); ui.horizontal(|ui| { ui.set_min_height(ui.spacing().interact_size.y); - let checkbox = is_enabled.as_deref_mut().map(|is_enabled| ui.checkbox(is_enabled, "")); - let title_response = ui.add(egui::Label::new(caption(title).color(text_color)).selectable(false)); - if let Some(checkbox) = checkbox { - checkbox_rect = Some(checkbox.rect); - checkbox.labelled_by(title_response.id); - } - - if collapsing_state.is_some() { - arrow_rect = Some( - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.allocate_exact_size(egui::vec2(ui.spacing().indent, ui.spacing().icon_width), egui::Sense::hover()).0 - }) - .inner, - ); - } - }); + ui.add(egui::Label::new(caption(title).color(tokens.text_strong)).selectable(false)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.allocate_exact_size(egui::vec2(ui.spacing().indent, ui.spacing().icon_width), egui::Sense::hover()).0 + }) + .inner + }) + .inner }); - if let (Some(collapsing_state), Some(arrow_rect)) = (collapsing_state, arrow_rect) { - let mut toggle_rect = header.response.rect; - if let Some(checkbox_rect) = checkbox_rect { - let checkbox_margin = ui.spacing().item_spacing.x * 0.5; - if ui.style().right_to_left { - toggle_rect.max.x = checkbox_rect.left() - checkbox_margin; - } else { - toggle_rect.min.x = checkbox_rect.right() + checkbox_margin; - } - } - - let response = ui.interact(toggle_rect, ui.make_persistent_id("section_header"), egui::Sense::click()); - if response.clicked() { - collapsing_state.toggle(ui); - } - - let chevron = crate::widgets::section_chevron(ui, collapsing_state.is_open()); - ui.put(arrow_rect, egui::Label::new(chevron).selectable(false)); + let response = ui.interact(header.response.rect, ui.make_persistent_id("section_header"), egui::Sense::click()); + if response.clicked() { + collapsing_state.toggle(ui); } - is_enabled.as_deref().copied().unwrap_or(true) + let chevron = crate::widgets::section_chevron(ui, collapsing_state.is_open()); + ui.put(header.inner, egui::Label::new(chevron).selectable(false)); } -pub(super) fn section(ui: &mut Ui, title: &str, is_enabled: Option<&mut bool>, contents: impl FnOnce(&mut Ui)) -> bool { +/// A collapsible section with `contents` and Restore Defaults; returns whether that was clicked +pub(super) fn section(ui: &mut Ui, title: &str, contents: impl FnOnce(&mut Ui)) -> bool { let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("section"), true); - if !section_header(ui, title, is_enabled, Some(&mut collapsing_state)) { - collapsing_state.store(ui.ctx()); - return false; - } + section_header(ui, title, &mut collapsing_state); collapsing_state .show_body_unindented(ui, |ui| { diff --git a/crates/ui-egui/src/bake_mode/map_settings.rs b/crates/ui-egui/src/bake_mode/map_settings.rs index a8cb2d48..0b5ac9e0 100644 --- a/crates/ui-egui/src/bake_mode/map_settings.rs +++ b/crates/ui-egui/src/bake_mode/map_settings.rs @@ -1,32 +1,34 @@ -use super::controls::{choice, integer, number, section, section_header}; -use crate::i18n::{baked_map_label, tr}; +use super::controls::{choice, hint, integer, number}; +use crate::i18n::tr; use egui::Ui; use texturecraft_engine::core::{ AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakedMap, BentNormalSettings, CurvatureMethod, CurvatureSettings, HeightNormalization, - HeightSettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshMapSettings, PositionAxis, PositionMode, PositionNormalizationScale, - PositionSettings, RayDistribution, RaySettings, SelfOcclusion, ThicknessNormalization, ThicknessSettings, + HeightSettings, IdColorGenerator, IdColorSource, IdSettings, MeshMapSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, + RayDistribution, RaySettings, SelfOcclusion, ThicknessNormalization, ThicknessSettings, }; +/// Draw `map`'s parameters with Restore Defaults; maps without parameters say so pub(super) fn show(ui: &mut Ui, map: BakedMap, settings: &mut MeshMapSettings) { match map { - BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => { - let mut is_enabled = settings.is_enabled(map); - section_header(ui, tr(baked_map_label(map)), Some(&mut is_enabled), None); - settings.set_enabled(map, is_enabled); - } - BakedMap::Id => baker(ui, map, &mut settings.id, id), - BakedMap::AmbientOcclusion => baker(ui, map, &mut settings.ao, ambient_occlusion), - BakedMap::Curvature => baker(ui, map, &mut settings.curvature, curvature), - BakedMap::Position => baker(ui, map, &mut settings.position, position), - BakedMap::Thickness => baker(ui, map, &mut settings.thickness, thickness), - BakedMap::Height => baker(ui, map, &mut settings.height, height), - BakedMap::BentNormal => baker(ui, map, &mut settings.bent_normal, bent_normal), + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => hint(ui, tr("No Parameters")), + BakedMap::Id => parameters(ui, &mut settings.id.parameters, id), + BakedMap::AmbientOcclusion => parameters(ui, &mut settings.ao.parameters, ambient_occlusion), + BakedMap::Curvature => parameters(ui, &mut settings.curvature.parameters, curvature), + BakedMap::Position => parameters(ui, &mut settings.position.parameters, position), + BakedMap::Thickness => parameters(ui, &mut settings.thickness.parameters, thickness), + BakedMap::Height => parameters(ui, &mut settings.height.parameters, height), + BakedMap::BentNormal => parameters(ui, &mut settings.bent_normal.parameters, bent_normal), } } -fn baker(ui: &mut Ui, map: BakedMap, settings: &mut MapSettings, controls: impl FnOnce(&mut Ui, &mut T)) { - if section(ui, tr(baked_map_label(map)), Some(&mut settings.is_enabled), |ui| controls(ui, &mut settings.parameters)) { - settings.parameters = T::default(); +/// A map's controls, then a right-aligned Restore Defaults that resets only its parameters +fn parameters(ui: &mut Ui, parameters: &mut T, controls: impl FnOnce(&mut Ui, &mut T)) { + controls(ui, parameters); + ui.add_space(6.0); + + let restore = ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| ui.button(tr("Restore Defaults"))).inner; + if restore.clicked() { + *parameters = T::default(); } } diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs new file mode 100644 index 00000000..b9101e93 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -0,0 +1,75 @@ +use egui::{Align, Layout, RichText, Sense, Stroke, Ui, UiBuilder, vec2}; +use egui_phosphor::regular as icon; +use texturecraft_engine::core::{BakeSettings, BakedMap}; + +use crate::TextureCraftApp; +use crate::docking::Panel; +use crate::i18n::{baked_map_label, tr}; +use crate::theme::Tokens; + +/// Height of one baker row, in points +const ROW_HEIGHT: f32 = 24.0; +/// Inset of a row's checkbox and name from its left edge, in points +const ROW_INSET: f32 = 6.0; + +/// The Common Settings button, Check All, and one row per map (checkbox enables, click selects) +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { + if ui.button(format!("{} {}", icon::GEAR, tr("Common Settings"))).clicked() { + app.ui.dock.focus(Panel::CommonSettings); + } + + ui.add_space(4.0); + check_all(ui, settings); + ui.separator(); + + let selected = super::selected_map(app.ui.selected_baked_map, settings); + for map in BakedMap::ALL { + if ui.push_id(map, |ui| row(ui, map, settings, map == selected)).inner { + app.ui.selected_baked_map = Some(map); + app.ui.dock.focus(Panel::MeshMapSettings); + } + } +} + +/// Enable every map, or disable them all when every map is already enabled +fn check_all(ui: &mut Ui, settings: &mut BakeSettings) { + let enabled_count = BakedMap::ALL.into_iter().filter(|map| settings.maps.is_enabled(*map)).count(); + let mut all_enabled = enabled_count == BakedMap::ALL.len(); + let some_enabled = enabled_count > 0 && !all_enabled; + + if ui.add(egui::Checkbox::new(&mut all_enabled, tr("Check All")).indeterminate(some_enabled)).changed() { + for map in BakedMap::ALL { + settings.maps.set_enabled(map, all_enabled); + } + } +} + +/// One baker row; returns whether the row (not its checkbox) was clicked +fn row(ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool) -> bool { + let tokens = Tokens::get(ui.ctx()); + let name = tr(baked_map_label(map)); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, is_selected, name)); + + let painter = ui.painter(); + if is_selected { + painter.rect_filled(rect, tokens.cr(), tokens.row_selected); + painter.rect_stroke(rect, tokens.cr(), Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(rect, tokens.cr(), tokens.row_hover); + } + painter.hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, tokens.separator)); + + // Added after the row's own response, so the checkbox takes the clicks over it + let content_rect = rect.shrink2(vec2(ROW_INSET, 0.0)); + let mut content = ui.new_child(UiBuilder::new().max_rect(content_rect).layout(Layout::left_to_right(Align::Center))); + let mut is_enabled = settings.maps.is_enabled(map); + let checkbox = content.checkbox(&mut is_enabled, ""); + let text = if is_selected { RichText::new(name).strong() } else { RichText::new(name) }; + let label = content.add(egui::Label::new(text).selectable(false).truncate()); + if checkbox.labelled_by(label.id).changed() { + settings.maps.set_enabled(map, is_enabled); + } + + response.clicked() +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 11de63af..789ddc51 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -24,8 +24,12 @@ use crate::theme::Tokens; pub enum Panel { Viewport, Assets, - BakeMaps, - BakeSettings, + // Saved layouts name the bake panels by their earlier names + #[serde(rename = "BakeMaps")] + MeshMapSettings, + #[serde(rename = "BakeSettings")] + CommonSettings, + MeshMapBakers, TextureSetList, Layers, TextureSetSettings, @@ -37,14 +41,15 @@ pub enum Panel { } /// Window ▸ Views items and the panels they show or hide. -pub const VIEWS: [(&str, Panel); 11] = [ +pub const VIEWS: [(&str, Panel); 12] = [ ("ui.view.assets", Panel::Assets), - ("ui.view.bakeMaps", Panel::BakeMaps), - ("ui.view.bakeSettings", Panel::BakeSettings), + ("ui.view.bakeMaps", Panel::MeshMapSettings), + ("ui.view.bakeSettings", Panel::CommonSettings), ("ui.view.display", Panel::Display), ("ui.view.history", Panel::History), ("ui.view.layers", Panel::Layers), ("ui.view.log", Panel::Log), + ("ui.view.meshMapBakers", Panel::MeshMapBakers), ("ui.view.properties", Panel::Properties), ("ui.view.shader", Panel::Shader), ("ui.view.textureSetList", Panel::TextureSetList), @@ -59,17 +64,18 @@ pub fn view_panel(id: &str) -> Option { impl Panel { pub(crate) fn available_in(self, mode: crate::state::Mode) -> bool { match self { - Self::BakeMaps | Self::BakeSettings => mode == crate::state::Mode::Baking, + Self::MeshMapSettings | Self::CommonSettings | Self::MeshMapBakers => mode == crate::state::Mode::Baking, Self::Assets | Self::Layers | Self::Properties | Self::TextureSetSettings => mode != crate::state::Mode::Baking, _ => true, } } - pub const ALL: [Panel; 12] = [ + pub const ALL: [Panel; 13] = [ Panel::Viewport, Panel::Assets, - Panel::BakeMaps, - Panel::BakeSettings, + Panel::MeshMapSettings, + Panel::CommonSettings, + Panel::MeshMapBakers, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, @@ -84,8 +90,9 @@ impl Panel { match self { Panel::Viewport => "Viewport", Panel::Assets => "Assets", - Panel::BakeMaps => "Bake Maps", - Panel::BakeSettings => "Settings", + Panel::MeshMapSettings => "Mesh Map Settings", + Panel::CommonSettings => "Common Settings", + Panel::MeshMapBakers => "Mesh Map Bakers", Panel::TextureSetList => "Texture Sets", Panel::Layers => "Layers", Panel::TextureSetSettings => "Texture Set Settings", @@ -122,8 +129,8 @@ fn tabs(panels: &[Panel]) -> Node { Node::Tabs { panels: panels.to_vec(), active: 0 } } -fn split(axis: SplitAxis, ratio: f32, first: Node, second: Node) -> Node { - Node::Split { axis, size: SplitSize::Ratio(ratio), first: Box::new(first), second: Box::new(second) } +fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node) -> Node { + Node::Split { axis, size, first: Box::new(first), second: Box::new(second) } } /// The default: assets left of the viewport; texture set list, layers (tabbed with the texture @@ -131,9 +138,14 @@ fn split(axis: SplitAxis, ratio: f32, first: Node, second: Node) - /// shader, history and log are closed and open as floating windows. pub fn default_workspace() -> Workspace { use Panel::*; - let column = - split(SplitAxis::Vertical, 0.125, tabs(&[TextureSetList]), split(SplitAxis::Vertical, 0.57, tabs(&[Layers, TextureSetSettings]), tabs(&[Properties]))); - let root = split(SplitAxis::Horizontal, 0.115, tabs(&[Assets]), split(SplitAxis::Horizontal, 0.78, tabs(&[Viewport]), column)); + let column = split( + SplitAxis::Vertical, + SplitSize::Ratio(0.125), + tabs(&[TextureSetList]), + split(SplitAxis::Vertical, SplitSize::Ratio(0.57), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), + ); + let root = + split(SplitAxis::Horizontal, SplitSize::Ratio(0.115), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.78), tabs(&[Viewport]), column)); let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() }); for panel in Panel::ALL { if let Some(rect) = panel.float_rect() { @@ -149,7 +161,7 @@ pub fn default_workspace() -> Workspace { workspace.hidden.push((panel, location)); } } - for panel in [BakeMaps, BakeSettings] { + for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] { workspace.hidden.push(( panel, Location { @@ -206,17 +218,28 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> { // --------------------------------------------------------------------------------------------- // The live dock +/// Width of the bake layout's texture set and mesh map bakers column, in points +const BAKERS_COLUMN_WIDTH: f32 = 200.0; +/// Width of the bake layout's common and mesh map settings column, in points +const SETTINGS_COLUMN_WIDTH: f32 = 330.0; +/// Height of the log under the bake layout's columns, in points +const BAKING_LOG_HEIGHT: f32 = 160.0; +/// Share of the first bake column the texture set list takes above the mesh map bakers +const TEXTURE_SET_LIST_SHARE: f32 = 0.4; + /// The dock layout (part of `UiState`; serialized as a craft-ui `Workspace`). #[derive(Clone, Debug)] pub struct Dock { workspace: Workspace, /// A panel to bring in front of the other floating windows on the next frame. raise: Option, + /// A saved layout could not be read, so this is the painting default in its place + replaced_unreadable: bool, } impl Default for Dock { fn default() -> Self { - Dock { workspace: default_workspace(), raise: None } + Dock { workspace: default_workspace(), raise: None, replaced_unreadable: false } } } @@ -240,18 +263,27 @@ impl<'de> Deserialize<'de> for Dock { } impl Dock { - /// The dock for a saved layout; the default when it is not a valid workspace. + /// The dock for a saved layout; the default, marked as a replacement, when it is not a valid workspace pub fn from_value(value: Value) -> Dock { + let unreadable = Dock { replaced_unreadable: true, ..Dock::default() }; let default = default_workspace(); let loaded = serde_json::from_value::(value).ok(); - let Some(mut workspace) = loaded.filter(|w| validate(w).is_ok()) else { return Dock::default() }; + let Some(mut workspace) = loaded.filter(|w| validate(w).is_ok()) else { return unreadable }; + workspace.reconcile(|_| true, permissions, &default); if validate(&workspace).is_err() { - return Dock::default(); + return unreadable; } - Dock { workspace, raise: None } + + Dock { workspace, raise: None, replaced_unreadable: false } } + /// Whether a saved layout could not be read and this dock is the painting default instead + pub(crate) fn replaced_unreadable(&self) -> bool { + self.replaced_unreadable + } + + /// Texture sets over the bakers, the two settings tabs, the log under both, then the viewport pub(crate) fn for_baking() -> Self { let mut workspace = default_workspace(); for panel in [Panel::Assets, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] { @@ -259,17 +291,19 @@ impl Dock { workspace.hidden.push((panel, location)); } } - workspace.hidden.retain(|(panel, _)| !matches!(panel, Panel::BakeMaps | Panel::BakeSettings)); - workspace.layout = Layout { - root: Some(Node::Split { - axis: SplitAxis::Horizontal, - size: SplitSize::FixedFirst(320.0), - first: Box::new(tabs(&[Panel::TextureSetList, Panel::BakeSettings, Panel::BakeMaps])), - second: Box::new(tabs(&[Panel::Viewport])), - }), - floating: Vec::new(), - }; - Dock { workspace, raise: None } + + let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::Log]; + workspace.hidden.retain(|(panel, _)| !bake_panels.contains(panel)); + + let gutter_width = f32::from(crate::theme::GUTTER); + let list_column = split(SplitAxis::Vertical, SplitSize::Ratio(TEXTURE_SET_LIST_SHARE), tabs(&[Panel::TextureSetList]), tabs(&[Panel::MeshMapBakers])); + let settings_column = tabs(&[Panel::CommonSettings, Panel::MeshMapSettings]); + let columns = split(SplitAxis::Horizontal, SplitSize::FixedFirst(BAKERS_COLUMN_WIDTH), list_column, settings_column); + let columns_over_log = split(SplitAxis::Vertical, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::Log])); + let columns_width = BAKERS_COLUMN_WIDTH + gutter_width + SETTINGS_COLUMN_WIDTH; + let root = split(SplitAxis::Horizontal, SplitSize::FixedFirst(columns_width), columns_over_log, tabs(&[Panel::Viewport])); + workspace.layout = Layout { root: Some(root), floating: Vec::new() }; + Dock { workspace, raise: None, replaced_unreadable: false } } pub fn workspace(&self) -> &Workspace { @@ -401,9 +435,10 @@ impl DockContent for Panels<'_> { return; } egui::Frame::new().inner_margin(Margin::symmetric(8, 4)).show(ui, |ui| match panel { - Panel::BakeMaps => crate::bake_mode::bake_body(app, ui), + Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), Panel::Assets => crate::shelf::body(app, ui), - Panel::BakeSettings => crate::bake_mode::settings_body(app, ui), + Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui), + Panel::MeshMapBakers => crate::bake_mode::mesh_map_bakers_panel(app, ui), Panel::TextureSetList if app.ui.mode == crate::state::Mode::Baking => crate::bake_mode::texture_sets(app, ui), Panel::TextureSetList => crate::dock::texture_set_list(app, ui), Panel::Layers => crate::dock::layers(app, ui), @@ -425,8 +460,6 @@ impl DockContent for Panels<'_> { fn logical_label(&self, panel: &Panel) -> String { match panel { Panel::Properties => crate::dock::properties_title(self.app), - Panel::BakeMaps => tr("Bake Maps").to_string(), - Panel::BakeSettings => tr("Settings").to_string(), p => tr(p.name()).to_string(), } } @@ -475,6 +508,20 @@ mod tests { assert_eq!(back, dock); } + #[test] + fn the_bake_dock_round_trips_with_the_log_under_both_settings_columns() { + let dock = Dock::for_baking(); + assert!(validate(dock.workspace()).is_ok()); + assert_eq!( + panels_of(dock.workspace()), + [Panel::TextureSetList, Panel::MeshMapBakers, Panel::CommonSettings, Panel::MeshMapSettings, Panel::Log, Panel::Viewport] + ); + assert!(dock.is_visible(Panel::CommonSettings) && !dock.is_visible(Panel::MeshMapSettings)); + + let back: Dock = serde_json::from_str(&serde_json::to_string(&dock).unwrap()).unwrap(); + assert_eq!(back, dock); + } + #[test] fn unreadable_layouts_become_the_default() { for text in [ diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 6ef517e9..405ee0b7 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -963,7 +963,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "توسيط النواظم"), ("BBox", "صندوق الإحاطة"), ("BSphere", "كرة الإحاطة"), - ("Bake Maps", "خبز الخرائط"), + ("Mesh Map Bakers", "مُخبِزات خرائط المجسم"), + ("Common Settings", "الإعدادات المشتركة"), + ("Mesh Map Settings", "إعدادات خرائط المجسم"), + ("Check All", "تحديد الكل"), + ("No Parameters", "لا توجد معلمات"), ("Bake Selected Textures ({n})", "خبز الخامات المحددة ({n})"), ("By Mesh Name", "حسب اسم المجسم"), ("Cage", "القفص"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index caaabb14..05778fa7 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1012,7 +1012,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Normalen mitteln"), ("BBox", "Begrenzungsrahmen"), ("BSphere", "Begrenzungskugel"), - ("Bake Maps", "Maps backen"), + ("Mesh Map Bakers", "Mesh-Map-Baker"), + ("Common Settings", "Allgemeine Einstellungen"), + ("Mesh Map Settings", "Mesh-Map-Einstellungen"), + ("Check All", "Alle auswählen"), + ("No Parameters", "Keine Parameter"), ("Bake Selected Textures ({n})", "Ausgewählte Texturen backen ({n})"), ("By Mesh Name", "Nach Mesh-Name"), ("Cage", "Käfig"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 6c8ccccb..8c1945f9 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -997,7 +997,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Promediar normales"), ("BBox", "Caja delimitadora"), ("BSphere", "Esfera delimitadora"), - ("Bake Maps", "Hornear mapas"), + ("Mesh Map Bakers", "Horneadores de mapas de malla"), + ("Common Settings", "Ajustes comunes"), + ("Mesh Map Settings", "Ajustes de mapas de malla"), + ("Check All", "Marcar todo"), + ("No Parameters", "Sin parámetros"), ("Bake Selected Textures ({n})", "Hornear texturas seleccionadas ({n})"), ("By Mesh Name", "Por nombre de malla"), ("Cage", "Jaula"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f10bba8d..a55060c5 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1021,7 +1021,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Moyenne des normales"), ("BBox", "Boîte englobante"), ("BSphere", "Sphère englobante"), - ("Bake Maps", "Précalculer les cartes"), + ("Mesh Map Bakers", "Précalculateurs de cartes de maillage"), + ("Common Settings", "Paramètres communs"), + ("Mesh Map Settings", "Paramètres des cartes de maillage"), + ("Check All", "Tout cocher"), + ("No Parameters", "Aucun paramètre"), ("Bake Selected Textures ({n})", "Précalculer les textures sélectionnées ({n})"), ("By Mesh Name", "Par nom de maillage"), ("Cage", "Cage"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1c19d597..2467f2e7 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1006,7 +1006,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Normali medie"), ("BBox", "Riquadro di delimitazione"), ("BSphere", "Sfera di delimitazione"), - ("Bake Maps", "Bake delle mappe"), + ("Mesh Map Bakers", "Baker delle mappe mesh"), + ("Common Settings", "Impostazioni comuni"), + ("Mesh Map Settings", "Impostazioni mappe mesh"), + ("Check All", "Seleziona tutto"), + ("No Parameters", "Nessun parametro"), ("Bake Selected Textures ({n})", "Bake texture selezionate ({n})"), ("By Mesh Name", "Per nome della mesh"), ("Cage", "Gabbia"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 068603b5..f6237ce4 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -991,7 +991,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "法線を平均化"), ("BBox", "バウンディングボックス"), ("BSphere", "バウンディングスフィア"), - ("Bake Maps", "マップをベイク"), + ("Mesh Map Bakers", "メッシュマップベイカー"), + ("Common Settings", "共通設定"), + ("Mesh Map Settings", "メッシュマップ設定"), + ("Check All", "すべてチェック"), + ("No Parameters", "パラメーターなし"), ("Bake Selected Textures ({n})", "選択したテクスチャをベイク ({n})"), ("By Mesh Name", "メッシュ名で"), ("Cage", "ケージ"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 137d6177..e1b9d52a 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -976,7 +976,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "노멀 평균화"), ("BBox", "경계 상자"), ("BSphere", "경계 구"), - ("Bake Maps", "맵 베이크"), + ("Mesh Map Bakers", "메시 맵 베이커"), + ("Common Settings", "공통 설정"), + ("Mesh Map Settings", "메시 맵 설정"), + ("Check All", "모두 선택"), + ("No Parameters", "매개변수 없음"), ("Bake Selected Textures ({n})", "선택한 텍스처 베이크 ({n})"), ("By Mesh Name", "메시 이름으로"), ("Cage", "케이지"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 99627b25..0a8fbfcd 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -994,7 +994,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Normais médias"), ("BBox", "Caixa delimitadora"), ("BSphere", "Esfera delimitadora"), - ("Bake Maps", "Bake de mapas"), + ("Mesh Map Bakers", "Bakers de mapas de malha"), + ("Common Settings", "Configurações comuns"), + ("Mesh Map Settings", "Configurações de mapas de malha"), + ("Check All", "Marcar todos"), + ("No Parameters", "Sem parâmetros"), ("Bake Selected Textures ({n})", "Fazer bake das texturas selecionadas ({n})"), ("By Mesh Name", "Por nome da malha"), ("Cage", "Gaiola"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 18623ce3..ec87af5d 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -922,7 +922,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "平均法线"), ("BBox", "包围盒"), ("BSphere", "包围球"), - ("Bake Maps", "烘焙贴图"), + ("Mesh Map Bakers", "网格贴图烘焙器"), + ("Common Settings", "通用设置"), + ("Mesh Map Settings", "网格贴图设置"), + ("Check All", "全选"), + ("No Parameters", "无参数"), ("Bake Selected Textures ({n})", "烘焙所选纹理({n})"), ("By Mesh Name", "按网格名称"), ("Cage", "笼形"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a2e85bf7..7890d436 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -61,12 +61,13 @@ pub const CATALOG: &[Item] = &[ it("Mode", "Painting", "ui.mode.paint", Some("F9")), it("Mode", "Rendering (path traced)", "ui.mode.render", Some("F10")), sub("Window", "Views", "Assets", "ui.view.assets", None), - sub("Window", "Views", "Bake Maps", "ui.view.bakeMaps", None), - sub("Window", "Views", "Settings", "ui.view.bakeSettings", None), + sub("Window", "Views", "Common Settings", "ui.view.bakeSettings", None), sub("Window", "Views", "Display Settings", "ui.view.display", None), sub("Window", "Views", "History", "ui.view.history", None), sub("Window", "Views", "Layers", "ui.view.layers", None), sub("Window", "Views", "Log", "ui.view.log", None), + sub("Window", "Views", "Mesh Map Bakers", "ui.view.meshMapBakers", None), + sub("Window", "Views", "Mesh Map Settings", "ui.view.bakeMaps", None), sub("Window", "Views", "Properties", "ui.view.properties", None), sub("Window", "Views", "Shader Settings", "ui.view.shader", None), sub("Window", "Views", "Texture Sets", "ui.view.textureSetList", None), diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 89c12bb0..64f65fd3 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1,7 +1,7 @@ //! UI state (serde, so the control channel can read and drive it). use serde::{Deserialize, Serialize}; -use texturecraft_engine::core::Channel; +use texturecraft_engine::core::{BakedMap, Channel}; use crate::docking::Dock; use crate::keymap::Keymap; @@ -232,6 +232,9 @@ fn default_export_dir() -> String { } } +/// The bake layout's version: saved bake docks from an older one load as `Dock::for_baking` +const BAKE_LAYOUT_VERSION: u32 = 1; + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { pub mode: Mode, @@ -243,6 +246,12 @@ pub struct UiState { pub(crate) inactive_mode_dock: Dock, #[serde(default)] pub(crate) dock_is_baking: bool, + /// The bake layout version the bake dock was saved with; 0 before versions existed. + #[serde(default)] + pub(crate) bake_layout_version: u32, + /// The mesh map whose settings Mesh Map Settings shows; `None` follows the first enabled map. + #[serde(default)] + pub(crate) selected_baked_map: Option, /// Window ▸ Hide UI (Tab): only the viewport. pub hide_ui: bool, pub windows: Windows, @@ -283,7 +292,10 @@ pub struct UiState { } impl UiState { + /// Replace an outdated or unreadable saved bake dock by the bake layout, then give the mode its dock pub(crate) fn sync_mode_dock(&mut self) { + self.reset_outdated_bake_dock(); + let baking = self.mode == Mode::Baking; if baking != self.dock_is_baking { std::mem::swap(&mut self.dock, &mut self.inactive_mode_dock); @@ -291,6 +303,17 @@ impl UiState { } } + /// Replace a bake dock saved with an older bake layout, or one that could not be read, by the bake default + fn reset_outdated_bake_dock(&mut self) { + let bake_dock = if self.dock_is_baking { &mut self.dock } else { &mut self.inactive_mode_dock }; + if self.bake_layout_version >= BAKE_LAYOUT_VERSION && !bake_dock.replaced_unreadable() { + return; + } + + *bake_dock = Dock::for_baking(); + self.bake_layout_version = BAKE_LAYOUT_VERSION; + } + /// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, export /// settings and recent files. pub fn adopt_layout(&mut self, layout: UiState) { @@ -313,6 +336,8 @@ impl Default for UiState { dock: Dock::default(), inactive_mode_dock: Dock::for_baking(), dock_is_baking: false, + bake_layout_version: BAKE_LAYOUT_VERSION, + selected_baked_map: None, hide_ui: false, windows: Windows::default(), uv_zoom: 1.0, @@ -364,6 +389,74 @@ mod tests { assert_eq!(Prefs::default().data_folder, "", "the default is no choice"); } + #[test] + fn a_bake_dock_saved_before_the_bake_layout_version_loads_the_current_bake_layout() { + let old_bake_dock = serde_json::json!({"version": 2, "layout": {"root": {"Split": {"axis": "Horizontal", "size": {"FixedFirst": 320.0}, + "first": {"Tabs": {"panels": ["TextureSetList", "BakeSettings", "BakeMaps"], "active": 0}}, + "second": {"Tabs": {"panels": ["Viewport"], "active": 0}}}}, "floating": []}}); + for dock_is_baking in [false, true] { + let mut painting_dock = Dock::default(); + painting_dock.close(crate::docking::Panel::Assets); + let (bake_field, painting_field) = if dock_is_baking { ("dock", "inactive_mode_dock") } else { ("inactive_mode_dock", "dock") }; + let mut saved = serde_json::to_value(UiState::default()).unwrap(); + let fields = saved.as_object_mut().unwrap(); + fields.remove("bake_layout_version"); + fields.insert("dock_is_baking".into(), serde_json::json!(dock_is_baking)); + fields.insert("mode".into(), serde_json::to_value(if dock_is_baking { Mode::Baking } else { Mode::Painting }).unwrap()); + fields.insert(bake_field.into(), old_bake_dock.clone()); + fields.insert(painting_field.into(), serde_json::to_value(&painting_dock).unwrap()); + + let mut ui: UiState = serde_json::from_value(saved).unwrap(); + let loaded_bake_dock = if dock_is_baking { &ui.dock } else { &ui.inactive_mode_dock }; + assert!(!loaded_bake_dock.is_open(crate::docking::Panel::MeshMapBakers), "the old layout loads without the bakers list"); + + ui.sync_mode_dock(); + let (bake_dock, painting) = if dock_is_baking { (&ui.dock, &ui.inactive_mode_dock) } else { (&ui.inactive_mode_dock, &ui.dock) }; + assert_eq!(*bake_dock, Dock::for_baking()); + assert_eq!(*painting, painting_dock, "the painting layout is kept"); + + let mut reloaded: UiState = serde_json::from_value(serde_json::to_value(&ui).unwrap()).unwrap(); + reloaded.sync_mode_dock(); + assert_eq!(reloaded, ui, "a current layout is not reset again"); + } + } + + /// The app's own settings store: eframe keeps `UiState` as RON text under a key + #[derive(Default)] + struct MemoryStorage(std::collections::HashMap); + + impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.0.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + self.0.insert(key.to_string(), value); + } + + fn remove_string(&mut self, key: &str) { + self.0.remove(key); + } + + fn flush(&mut self) {} + } + + #[test] + fn the_bake_layout_survives_a_restart_whichever_mode_was_open() { + for mode in [Mode::Painting, Mode::Baking] { + let mut ui = UiState { mode, ..UiState::default() }; + ui.sync_mode_dock(); + let mut storage = MemoryStorage::default(); + eframe::set_value(&mut storage, "ui", &ui); + + let mut restarted: UiState = eframe::get_value(&storage, "ui").unwrap(); + restarted.sync_mode_dock(); + let bake_dock = if mode == Mode::Baking { &restarted.dock } else { &restarted.inactive_mode_dock }; + assert_eq!(*bake_dock, Dock::for_baking(), "{mode:?}"); + assert!(bake_dock.is_open(crate::docking::Panel::MeshMapBakers), "{mode:?}"); + } + } + #[test] fn older_saved_state_without_a_dock_loads_the_default_layout() { let mut v = serde_json::to_value(UiState::default()).unwrap(); diff --git a/crates/ui-egui/tests/bake_mode.rs b/crates/ui-egui/tests/bake_mode.rs index 409966c6..7f2020a0 100644 --- a/crates/ui-egui/tests/bake_mode.rs +++ b/crates/ui-egui/tests/bake_mode.rs @@ -1,3 +1,4 @@ +use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::core::{BakeResolution, BakedMap, CageType, CurvatureMethod, HeightNormalization}; @@ -5,6 +6,7 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; use texturecraft_ui_egui::state::Mode; +/// A bake-mode app with only `map` enabled and Mesh Map Settings in front fn harness(map: Option) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.doc.project.texture_sets[0].bake = Default::default(); @@ -13,11 +15,29 @@ fn harness(map: Option) -> Harness<'static, TextureCraftApp> { let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); - harness.state_mut().ui.dock.focus(Panel::BakeMaps); + harness.state_mut().ui.dock.focus(Panel::MeshMapSettings); harness.run_steps(3); harness } +/// The maps the first texture set will bake +fn enabled_maps(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.doc.project.texture_sets[0].bake.maps.enabled().collect() +} + +/// Click a map's row in Mesh Map Bakers, which shows its settings +fn select_map(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + harness.get_by_role_and_label(Role::Button, name).click(); + harness.run_steps(3); +} + +/// Click a checkbox in Mesh Map Bakers: a map's row or Check All +fn click_checkbox(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + harness.get_by_role_and_label(Role::CheckBox, name).click(); + harness.run_steps(3); +} + +/// Scroll the widget labelled `label` into view and click it fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { harness.get_by_label(label).scroll_to_me(); harness.run_steps(3); @@ -29,8 +49,8 @@ fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { fn output_axes_unlock_independently_and_relock_to_width() { let mut harness = harness(None); harness.get_by_label("Texture Sets"); - harness.get_by_label("Bake Maps"); - harness.state_mut().ui.dock.focus(Panel::BakeSettings); + harness.get_by_label("Mesh Map Settings"); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); let width = harness.state().session.doc.project.texture_sets[0].bake.common.resolution.pixels().to_string(); assert!(harness.get_all_by_value(&width).nth(1).unwrap().accesskit_node().is_disabled()); @@ -47,36 +67,86 @@ fn output_axes_unlock_independently_and_relock_to_width() { click(&mut harness, "Lock Output Size"); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.common.output_size(), (128, 128)); assert!(harness.get_all_by_value("128").nth(1).unwrap().accesskit_node().is_disabled()); - harness.state_mut().ui.dock.focus(Panel::BakeMaps); + harness.state_mut().ui.dock.focus(Panel::MeshMapSettings); harness.run_steps(3); - harness.state_mut().ui.dock.focus(Panel::BakeSettings); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); assert!(harness.get_all_by_value("128").nth(1).unwrap().accesskit_node().is_disabled()); harness.state_mut().ui.mode = Mode::Painting; harness.run_steps(3); - assert!(!harness.state().ui.dock.is_open(Panel::BakeSettings)); + assert!(!harness.state().ui.dock.is_open(Panel::CommonSettings)); assert!(harness.state().ui.dock.is_open(Panel::Assets)); } #[test] -fn height_controls_follow_enablement_and_manual_normalization() { +fn height_controls_follow_manual_normalization_and_the_row_checkbox_enables_height() { let mut harness = harness(None); assert!(harness.query_by_label("Normalization").is_none()); - click(&mut harness, "Height"); - assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); + select_map(&mut harness, "Height"); + assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled, "selecting is not enabling"); assert!(harness.query_by_label("Scaling Divisor").is_none()); click(&mut harness, "Normalization"); click(&mut harness, "Manual"); harness.get_by_label("Scaling Divisor"); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::Manual); - click(&mut harness, "Restore Defaults"); + click_checkbox(&mut harness, "Height"); assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); + click(&mut harness, "Restore Defaults"); + assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled, "Restore Defaults keeps the map enabled"); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::RelativeToLowMesh); assert!(harness.query_by_label("Scaling Divisor").is_none()); - click(&mut harness, "Height"); - assert!(harness.query_by_label("Normalization").is_none()); + click_checkbox(&mut harness, "Height"); + assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); +} + +#[test] +fn clicking_a_row_shows_that_maps_settings_without_changing_what_bakes() { + let mut harness = harness(Some(BakedMap::Curvature)); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + let before = enabled_maps(&harness); + + select_map(&mut harness, "Ambient Occlusion"); + assert!(harness.state().ui.dock.is_visible(Panel::MeshMapSettings), "selecting a map fronts its settings"); + harness.get_by_label("Attenuation"); + assert!(harness.query_by_label("Method").is_none()); + select_map(&mut harness, "Opacity"); + harness.get_by_label("No Parameters"); + assert!(harness.query_by_label("Attenuation").is_none()); + assert_eq!(enabled_maps(&harness), before); + + click(&mut harness, &format!("{} Common Settings", egui_phosphor::regular::GEAR)); + assert!(harness.state().ui.dock.is_visible(Panel::CommonSettings)); + assert_eq!(enabled_maps(&harness), before); +} + +#[test] +fn check_all_enables_every_map_then_disables_them_all() { + let mut harness = harness(Some(BakedMap::Curvature)); + click_checkbox(&mut harness, "Check All"); + assert_eq!(enabled_maps(&harness), BakedMap::ALL); + click_checkbox(&mut harness, "Check All"); + assert!(enabled_maps(&harness).is_empty()); +} + +#[test] +fn the_breadcrumb_switches_the_shown_map() { + let mut harness = harness(Some(BakedMap::Curvature)); + harness.get_by_label("Details"); + assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 1, "only the list row before the menu opens"); + let dropdowns: Vec<_> = harness.get_all_by_label(egui_phosphor::regular::CARET_RIGHT).collect(); + let [_texture_set_dropdown, map_dropdown] = dropdowns.as_slice() else { panic!("the breadcrumb has a texture set and a map dropdown") }; + map_dropdown.click(); + harness.run_steps(3); + assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 2, "the map menu lists Position"); + // The menu draws its items after the list rows + harness.get_all_by_role_and_label(Role::Button, "Position").last().unwrap().click(); + harness.run_steps(3); + harness.get_by_label("Normalization Scale"); + assert!(harness.query_by_label("Details").is_none()); + assert_eq!(enabled_maps(&harness), [BakedMap::Curvature]); } #[test] @@ -102,7 +172,7 @@ fn curvature_controls_follow_the_method_and_notes_visibility_rules() { #[test] fn cage_and_skew_controls_require_a_high_poly_and_follow_cage_type() { let mut harness = harness(None); - harness.state_mut().ui.dock.focus(Panel::BakeSettings); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); assert!(harness.query_by_label("Cage Type").is_none()); assert!(harness.query_by_label("Skew Correction").is_none()); diff --git a/crates/ui-egui/tests/skew_paint.rs b/crates/ui-egui/tests/skew_paint.rs index 1fd92400..bfcc3e3e 100644 --- a/crates/ui-egui/tests/skew_paint.rs +++ b/crates/ui-egui/tests/skew_paint.rs @@ -1,11 +1,12 @@ //! Bake mode: with the skew brush on, dragging in the 2D view paints the skew map, and the -//! brush controls are in the Bake panel. +//! brush controls are in Common Settings. use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{Mode, ViewLayout}; +/// A bake-mode app with a high poly, the 2D view, and Common Settings in front fn harness() -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); @@ -13,7 +14,7 @@ fn harness() -> Harness<'static, TextureCraftApp> { h.state_mut().ui.mode = Mode::Baking; h.state_mut().ui.layout = ViewLayout::Only2D; h.run_steps(4); - h.state_mut().ui.dock.focus(texturecraft_ui_egui::docking::Panel::BakeSettings); + h.state_mut().ui.dock.focus(texturecraft_ui_egui::docking::Panel::CommonSettings); h.run_steps(3); h } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 0f42158f..cbcb769b 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -14,6 +14,12 @@ use texturecraft_ui_egui::state::Mode; use texturecraft_ui_egui::theme::Brightness; use texturecraft_ui_egui::titlebar::TitleBar; +/// Click a map's row in Mesh Map Bakers, which shows its settings +fn select_map(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + harness.get_by_role_and_label(egui::Role::Button, name).click(); + harness.run_steps(3); +} + fn save(h: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { h.run_steps(6); let img = h.render().unwrap_or_else(|e| panic!("{name}: {e}")); @@ -58,18 +64,16 @@ fn window_snapshots() { } harness.state_mut().ui.mode = Mode::Baking; save(&mut harness, &output_dir, "mode-bake"); - harness.state_mut().ui.dock.focus(Panel::BakeMaps); - harness.run_steps(3); - harness.get_by_label("Ambient Occlusion").scroll_to_me(); + select_map(&mut harness, "Ambient Occlusion"); save(&mut harness, &output_dir, "mode-bake-maps"); harness.state_mut().ui.prefs.brightness = Brightness::Light; save(&mut harness, &output_dir, "mode-bake-maps-light"); harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; - harness.get_by_label("Opacity").scroll_to_me(); + select_map(&mut harness, "Opacity"); save(&mut harness, &output_dir, "mode-bake-unchecked"); harness.state_mut().ui.dock.focus(Panel::TextureSetList); save(&mut harness, &output_dir, "bake-texture-sets"); - harness.state_mut().ui.dock.focus(Panel::BakeSettings); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); save(&mut harness, &output_dir, "bake-settings"); harness.state_mut().session.add_high_poly_bytes("High Poly.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); save(&mut harness, &output_dir, "bake-settings-high-poly"); @@ -90,11 +94,9 @@ fn window_snapshots() { settings.maps.height.parameters.normalization = HeightNormalization::Manual; settings.maps.height.parameters.scaling_divisor = 100.0; } - harness.state_mut().ui.dock.focus(Panel::BakeMaps); - harness.run_steps(3); - harness.get_by_label("Curvature").scroll_to_me(); + select_map(&mut harness, "Curvature"); save(&mut harness, &output_dir, "bake-curvature-mesh"); - harness.get_by_label("Scaling Divisor").scroll_to_me(); + select_map(&mut harness, "Height"); save(&mut harness, &output_dir, "bake-height-manual"); harness.state_mut().session.bake_meshes.high.clear(); harness.state_mut().ui.mode = Mode::Painting; diff --git a/docs/parity.md b/docs/parity.md index d6543d54..652b84a9 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -2,7 +2,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Each row is a menu item of the target menu layout with TextureCraft's command id; **live** means the id is implemented. Feature parity beyond menus is tracked in [`ROADMAP.md`](../ROADMAP.md). -**55 of 55 menu items live (100%).** +**58 of 58 menu items live (100%).** ## File @@ -46,13 +46,16 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Item | Id | Shortcut | Status | |---|---|---|---| | Views ▸ Assets | `ui.view.assets` | | live | +| Views ▸ Common Settings | `ui.view.bakeSettings` | | live | | Views ▸ Display Settings | `ui.view.display` | | live | | Views ▸ History | `ui.view.history` | | live | | Views ▸ Layers | `ui.view.layers` | | live | | Views ▸ Log | `ui.view.log` | | live | +| Views ▸ Mesh Map Bakers | `ui.view.meshMapBakers` | | live | +| Views ▸ Mesh Map Settings | `ui.view.bakeMaps` | | live | | Views ▸ Properties | `ui.view.properties` | | live | | Views ▸ Shader Settings | `ui.view.shader` | | live | -| Views ▸ Texture Set List | `ui.view.textureSetList` | | live | +| Views ▸ Texture Sets | `ui.view.textureSetList` | | live | | Views ▸ Texture Set Settings | `ui.view.textureSetSettings` | | live | | Save UI Layout ▸ Save current layout... | `ui.layout.save` | | live | | Load UI Layout | `ui.layout.load` | | live | From 62da832811f89cd55461e50d6084192c4f858cf6 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 08:16:45 +0000 Subject: [PATCH 09/73] Draggable divider between the 3D and 2D views In the split layout the line between the views was fixed at the centre. It can now be dragged to resize both views live; the position is saved in UiState::split_ratio (serde default 0.5, so older states load). - Grab zone of 8 pt around the unchanged 2 pt line, claimed after the views so a press there never paints, orbits or pans. Resize cursor on hover and drag, no highlight. Left button only. - Either view can shrink to a 16 pt sliver. A view narrower than its 300 pt camera and view pickers hides them, and each view is clipped to its side of the divider. - Dragging keeps the 2D texture's on-screen size and offset from the view's centre (zoom and horizontal pan are compensated), stopping where that zoom would leave the 0.1-40 range the wheel uses. - The 2D view's edges sit on whole pixels and views render at the pixel size egui draws them at, so rounding can't nudge the texture's size. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/state.rs | 9 ++ crates/ui-egui/src/viewport.rs | 191 +++++++++++++++++++---- crates/ui-egui/tests/split_divider.rs | 209 ++++++++++++++++++++++++++ 3 files changed, 380 insertions(+), 29 deletions(-) create mode 100644 crates/ui-egui/tests/split_divider.rs diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 89c12bb0..8673fda0 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -232,10 +232,18 @@ fn default_export_dir() -> String { } } +/// The split layout starts with the 3D and 2D views at equal width +fn default_split_ratio() -> f32 { + 0.5 +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { pub mode: Mode, pub layout: ViewLayout, + /// The 3D view's share of the viewport width in the split layout + #[serde(default = "default_split_ratio")] + pub split_ratio: f32, /// The docked, tabbed and floating panels around the viewport. #[serde(default)] pub dock: Dock, @@ -310,6 +318,7 @@ impl Default for UiState { UiState { mode: Mode::Painting, layout: ViewLayout::Split, + split_ratio: default_split_ratio(), dock: Dock::default(), inactive_mode_dock: Dock::for_baking(), dock_is_baking: false, diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index da60a42d..78618f1e 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -3,6 +3,7 @@ use std::sync::Mutex; +use egui::emath::GuiRounding as _; use egui::{Color32, PointerButton, Pos2, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use serde_json::json; use texturecraft_engine::camera_cmds::DEFAULT_CAMERA; @@ -34,6 +35,7 @@ pub fn set_focus_picking(ctx: &egui::Context, on: bool) { ctx.data_mut(|d| d.insert_temp(focus_pick_id(), on)); } +/// The viewport dock tab: the paint bar, then the 3D and 2D views in the chosen layout with the mode's overlays pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let mode = app.ui.mode; let bake_painting = mode == crate::state::Mode::Baking @@ -43,6 +45,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { !texture_set.bake.high_poly.use_low_as_high && texture_set.bake.cage.kind == texturecraft_engine::core::CageType::DistanceBased }); app.ui.bake_paint_brush.on = bake_painting; + if !app.ui.hide_ui { crate::toolbar::paint_bar(app, ui); } @@ -50,27 +53,39 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let aux = match app.session.view { _ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing => Some(crate::gpu::AuxView::QuickMask), - ViewMode::MeshMap(m) => Some(crate::gpu::AuxView::MeshMap(m)), + ViewMode::MeshMap(map) => Some(crate::gpu::AuxView::MeshMap(map)), ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)), _ => None, }; let mut sync = PendingSync(Some(aux)); let full = ui.available_rect_before_wrap(); path_keys(app, ui); + // Skew painting needs the 2D view alongside the 3D Bake preview let layout = if mode == crate::state::Mode::Painting || bake_painting { app.ui.layout } else { ViewLayout::Only3D }; match layout { ViewLayout::Only3D => view_3d(app, ui, full, &mut sync), ViewLayout::Only2D => view_2d(app, ui, full, &mut sync), ViewLayout::Split => { - let midpoint = full.center().x; - let left = Rect::from_min_max(full.min, pos2(midpoint - 1.0, full.max.y)); - let right = Rect::from_min_max(pos2(midpoint + 1.0, full.min.y), full.max); + // The 2D view's edges sit on whole pixels, so rounding can't nudge a texture its zoom keeps at one size + let pixels_per_point = ui.ctx().pixels_per_point(); + let full = full.with_max_x(full.right().round_to_pixels(pixels_per_point)); + let divider_x = split_divider_x(app, ui, full); + let left = Rect::from_min_max(full.min, pos2(divider_x - SPLIT_LINE_HALF_WIDTH, full.max.y)); + let right = Rect::from_min_max(pos2(divider_x + SPLIT_LINE_HALF_WIDTH, full.min.y), full.max); + // Each view draws only on its side, so overlays such as the texture set name stay out of a narrow neighbour + let clip = ui.clip_rect(); + ui.set_clip_rect(left.intersect(clip)); view_3d(app, ui, left, &mut sync); + ui.set_clip_rect(right.intersect(clip)); view_2d(app, ui, right, &mut sync); - ui.painter().line_segment([pos2(midpoint, full.top()), pos2(midpoint, full.bottom())], Stroke::new(2.0, tokens.chrome)); + ui.set_clip_rect(clip); + split_divider_grab(ui, full, divider_x); + let line = Stroke::new(SPLIT_LINE_HALF_WIDTH * 2.0, tokens.chrome); + ui.painter().line_segment([pos2(divider_x, full.top()), pos2(divider_x, full.bottom())], line); } } + if mode == crate::state::Mode::Rendering { crate::render_mode::show(app, ui, full); } else if app.render.is_active() { @@ -79,17 +94,109 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { if mode == crate::state::Mode::Baking { crate::bake_mode::bake_bar(app, ui.ctx(), full); } + // Keep drawing until the 3D view finishes accumulating anti-aliasing samples let accumulating = layout != ViewLayout::Only2D - && app - .render_state - .as_ref() - .is_some_and(|rs| rs.renderer.read().callback_resources.get::().is_some_and(|g| g.renderer.accumulating(VIEW_3D))); + && app.render_state.as_ref().is_some_and(|render_state| { + render_state.renderer.read().callback_resources.get::().is_some_and(|gpu| gpu.renderer.accumulating(VIEW_3D)) + }); if app.session.stroke_active() || accumulating { ui.ctx().request_repaint(); } } +/// Half the split divider's line width: each view starts this far from the line's centre +const SPLIT_LINE_HALF_WIDTH: f32 = 1.0; + +/// Narrowest a split view may get: a sliver that is still easy to grab and drag back out +const MIN_SPLIT_VIEW_WIDTH: f32 = 16.0; + +/// Width of the split divider's grab zone, centred on its line +const SPLIT_DIVIDER_GRAB_WIDTH: f32 = 8.0; + +/// The split divider's widget id, shared by its drag read and its grab zone +fn split_divider_id(ui: &Ui) -> egui::Id { + ui.scope_id().with("split_divider") +} + +/// The 3D view's share of `width`, keeping both views at least [`MIN_SPLIT_VIEW_WIDTH`] wide when they fit +fn clamp_split_ratio(ratio: f32, width: f32) -> f32 { + let min_ratio = (MIN_SPLIT_VIEW_WIDTH / width).min(0.5); + let ratio = if ratio.is_finite() { ratio } else { 0.5 }; + ratio.clamp(min_ratio, 1.0 - min_ratio) +} + +/// The split divider's x position: while it is dragged it follows the pointer and changes the 2D zoom so the texture keeps its size on screen +fn split_divider_x(app: &mut TextureCraftApp, ui: &Ui, full: Rect) -> f32 { + // The 2D view's left edge, beside the line, sits on a whole pixel + let pixels_per_point = ui.ctx().pixels_per_point(); + let divider_x = |ratio: f32| { + let unsnapped = full.left() + full.width() * clamp_split_ratio(ratio, full.width()); + (unsnapped + SPLIT_LINE_HALF_WIDTH).round_to_pixels(pixels_per_point) - SPLIT_LINE_HALF_WIDTH + }; + let old_x = divider_x(app.ui.split_ratio); + + // Read the drag before the views lay out so they follow the pointer in the same frame + let ctx = ui.ctx(); + if ctx.is_being_dragged(split_divider_id(ui)) + && ctx.input(|i| i.pointer.primary_down()) + && let Some(pointer) = ctx.pointer_interact_pos() + { + // `max` and `min` rather than `clamp`, so a NaN bound from a corrupt saved zoom can't panic + let (min_x, max_x) = divider_range_keeping_uv_size(&app.ui, full, old_x, pixels_per_point); + let target_x = pointer.x.max(min_x).min(max_x); + app.ui.split_ratio = clamp_split_ratio((target_x - full.left()) / full.width(), full.width()); + let new_x = divider_x(app.ui.split_ratio); + keep_uv_view_on_screen(&mut app.ui, full, old_x, new_x); + } + + divider_x(app.ui.split_ratio) +} + +/// Lowest 2D zoom, for the wheel and the divider (inside the renderer's own limit of 0.05) +const UV_VIEW_MIN_ZOOM: f32 = 0.1; + +/// Highest 2D zoom, for the wheel and the divider (inside the renderer's own limit of 64) +const UV_VIEW_MAX_ZOOM: f32 = 40.0; + +/// The 2D view's width when the split divider is at `divider_x` +fn uv_view_width(full: Rect, divider_x: f32) -> f32 { + (full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0) +} + +/// The share of the 2D view's height that a zoom of 1 fills at `width`: the view fits the texture to its narrower side +fn uv_view_fit(full: Rect, width: f32) -> f32 { + (width / full.height().max(1.0)).min(1.0) +} + +/// The divider positions where the 2D zoom that keeps the texture's screen size stays inside the 2D zoom range +fn divider_range_keeping_uv_size(ui_state: &crate::state::UiState, full: Rect, old_x: f32, pixels_per_point: f32) -> (f32, f32) { + // The zoom times the fit is the texture's screen size, which a divider drag keeps + let screen_zoom = ui_state.uv_zoom * uv_view_fit(full, uv_view_width(full, old_x)); + + // Whole pixels, rounded inward, so snapping the divider to a pixel can't step past the range + let narrowest_view = (full.height() * screen_zoom / UV_VIEW_MAX_ZOOM * pixels_per_point).ceil() / pixels_per_point; + let widest_view = (full.height() * screen_zoom / UV_VIEW_MIN_ZOOM * pixels_per_point).floor() / pixels_per_point; + + let edge = full.right() - SPLIT_LINE_HALF_WIDTH; + (edge - widest_view, edge - narrowest_view) +} + +/// Keeps the 2D view's texture at the same size and offset from the view's centre when the divider moves its left edge from `old_x` to `new_x` +fn keep_uv_view_on_screen(ui_state: &mut crate::state::UiState, full: Rect, old_x: f32, new_x: f32) { + let (old_width, new_width) = (uv_view_width(full, old_x), uv_view_width(full, new_x)); + ui_state.uv_zoom *= uv_view_fit(full, old_width) / uv_view_fit(full, new_width); + + // The horizontal pan is in half view widths + ui_state.uv_pan[0] *= old_width / new_width; +} + +/// The split divider's grab zone with a resize cursor, claimed after the views so it wins the pointer over them +fn split_divider_grab(ui: &Ui, full: Rect, divider_x: f32) { + let zone = Rect::from_x_y_ranges(divider_x - SPLIT_DIVIDER_GRAB_WIDTH * 0.5..=divider_x + SPLIT_DIVIDER_GRAB_WIDTH * 0.5, full.y_range()); + ui.interact(zone, split_divider_id(ui), Sense::drag()).on_hover_and_drag_cursor(egui::CursorIcon::ResizeHorizontal); +} + fn shade(app: &TextureCraftApp) -> Shade { let (view_mode, channel) = match app.session.view { _ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing => (2, 0), @@ -167,6 +274,13 @@ const MAX_NAME_CHARS: usize = 32; /// that view handled its input: a stroke shows in the frame it is painted, not the next. pub struct PendingSync(Option>); +/// A view's render size in pixels, rounded as egui rounds the rect it draws the frame into, so the frame is never stretched +fn frame_size_in_pixels(ui: &Ui, rect: Rect) -> [u32; 2] { + let pixels_per_point = ui.ctx().pixels_per_point(); + let pixels = |from: f32, to: f32| ((to * pixels_per_point).round() - (from * pixels_per_point).round()).max(1.0) as u32; + [pixels(rect.left(), rect.right()), pixels(rect.top(), rect.bottom())] +} + fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, frame: Frame, sync: &mut PendingSync) { let tk = Tokens::get(ui.ctx()); let scene = match (sync.0.take(), app.gpu.as_mut()) { @@ -192,20 +306,38 @@ fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, frame: Frame, sy ui.painter().add(eframe::egui_wgpu::Callback::new_paint_callback(rect, cb)); } -/// The view-mode dropdown shown at the top of each view. +/// Width of the camera and view pickers centred at the top of a view +const VIEW_HEADER_WIDTH: f32 = 300.0; + +/// Height of the view pickers' row +const VIEW_HEADER_HEIGHT: f32 = 22.0; + +/// Gap between the view's top edge and its pickers +const VIEW_HEADER_TOP_GAP: f32 = 8.0; + +/// Width of each of the two pickers +const VIEW_PICKER_WIDTH: f32 = 130.0; + +/// The camera and view pickers at the top of a view, left out when the view is too narrow to hold them fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { - let header = Rect::from_min_size(rect.min + vec2(rect.width() * 0.5 - 150.0, 8.0), vec2(300.0, 22.0)); + if rect.width() < VIEW_HEADER_WIDTH { + return; + } + + let header_min = rect.min + vec2((rect.width() - VIEW_HEADER_WIDTH) * 0.5, VIEW_HEADER_TOP_GAP); + let header = Rect::from_min_size(header_min, vec2(VIEW_HEADER_WIDTH, VIEW_HEADER_HEIGHT)); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(header).layout(egui::Layout::left_to_right(egui::Align::Center))); + let current = texturecraft_engine::camera_cmds::current(&app.session); - let names: Vec = app.session.doc.project.cameras.iter().map(|c| c.name.clone()).collect(); - let shown = current.and_then(|i| names.get(i)).map_or(tr(DEFAULT_CAMERA), String::as_str); - egui::ComboBox::from_id_salt(format!("{id}_cam")).width(130.0).selected_text(shown).show_ui(&mut child, |ui| { + let names: Vec = app.session.doc.project.cameras.iter().map(|camera| camera.name.clone()).collect(); + let shown = current.and_then(|index| names.get(index)).map_or(tr(DEFAULT_CAMERA), String::as_str); + egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| { if ui.selectable_label(current.is_none(), tr(DEFAULT_CAMERA)).clicked() { app.run("camera.select", json!({})); } - for (i, name) in names.iter().enumerate() { - if ui.selectable_label(current == Some(i), name).clicked() { - app.run("camera.select", json!({"index": i})); + for (index, name) in names.iter().enumerate() { + if ui.selectable_label(current == Some(index), name).clicked() { + app.run("camera.select", json!({"index": index})); } } ui.separator(); @@ -213,26 +345,27 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { app.run("camera.add", json!({})); } }); + let label = match app.session.view { ViewMode::MeshMap(map) => crate::i18n::baked_map_label(map).to_owned(), _ => app.session.view.label(), }; - let channels = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); - egui::ComboBox::from_id_salt(format!("{id}_mode")).width(130.0).selected_text(tr(&label)).show_ui(&mut child, |ui| { + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); + egui::ComboBox::from_id_salt(format!("{id}_mode")).width(VIEW_PICKER_WIDTH).selected_text(tr(&label)).show_ui(&mut child, |ui| { if ui.selectable_label(app.session.view == ViewMode::Material, tr("Material")).clicked() { app.run("viewport.view", json!({"mode": "material"})); } ui.separator(); - for c in channels { - if ui.selectable_label(app.session.view == ViewMode::Channel(c), tr(c.label())).clicked() { - app.run("viewport.view", json!({"mode": c.id()})); + for channel in channels { + if ui.selectable_label(app.session.view == ViewMode::Channel(channel), tr(channel.label())).clicked() { + app.run("viewport.view", json!({"mode": channel.id()})); } } ui.separator(); - for m in BakedMap::ALL { - if ui.selectable_label(app.session.view == ViewMode::MeshMap(m), trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(m)))])).clicked() - { - app.run("viewport.view", json!({"mode": format!("map:{}", m.id())})); + for map in BakedMap::ALL { + let map_label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]); + if ui.selectable_label(app.session.view == ViewMode::MeshMap(map), map_label).clicked() { + app.run("viewport.view", json!({"mode": format!("map:{}", map.id())})); } } ui.separator(); @@ -429,7 +562,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let frame = Frame { view_id: crate::viewport::VIEW_3D, - size: [(size.x * ui.ctx().pixels_per_point()).max(1.0) as u32, (size.y * ui.ctx().pixels_per_point()).max(1.0) as u32], + size: frame_size_in_pixels(ui, rect), kind: ViewKind::Scene, camera: app.session.camera, shade: shade(app), @@ -968,7 +1101,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let scroll = ui.input(|i| i.smooth_scroll_delta.y); if scroll != 0.0 { let old = app.ui.uv_zoom; - let new = (old * (1.0 + scroll * 0.002)).clamp(0.1, 40.0); + let new = (old * (1.0 + scroll * 0.002)).clamp(UV_VIEW_MIN_ZOOM, UV_VIEW_MAX_ZOOM); // Zoom about the cursor. if let Some(hp) = resp.hover_pos() { let c = [(hp.x - rect.left()) / size.x * 2.0 - 1.0, 1.0 - (hp.y - rect.top()) / size.y * 2.0]; @@ -1042,7 +1175,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } let frame = Frame { view_id: VIEW_2D, - size: [(size.x * ui.ctx().pixels_per_point()).max(1.0) as u32, (size.y * ui.ctx().pixels_per_point()).max(1.0) as u32], + size: frame_size_in_pixels(ui, rect), kind: ViewKind::Uv { ts, zoom: app.ui.uv_zoom, pan: app.ui.uv_pan }, camera: app.session.camera, shade: shade(app), diff --git a/crates/ui-egui/tests/split_divider.rs b/crates/ui-egui/tests/split_divider.rs new file mode 100644 index 00000000..d5af8c8f --- /dev/null +++ b/crates/ui-egui/tests/split_divider.rs @@ -0,0 +1,209 @@ +//! The divider between the 3D and 2D views in the split layout resizes them and keeps the pointer from the views + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use texturecraft_engine::core::Channel; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::UiState; + +/// Narrowest a split view may get, as in `viewport.rs` +const MIN_VIEW_WIDTH: f32 = 16.0; + +/// A press clear of the divider's 8 point grab zone and egui's 5 point interact radius +const BESIDE_DIVIDER: f32 = 16.0; + +/// App storage held in memory, saved the way the app saves its state between runs +#[derive(Default)] +struct MemoryStorage(std::collections::HashMap); + +impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.0.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + self.0.insert(key.to_owned(), value); + } + + fn remove_string(&mut self, key: &str) { + self.0.remove(key); + } + + fn flush(&mut self) {} +} + +/// The sample project in the default split layout at 1600 x 960 +fn split_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness +} + +/// Drag with `button` from `from` to `to` in a few moves +fn drag(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + for step in 1..=4 { + harness.hover_at(from + (to - from) * (step as f32 / 4.0)); + harness.run_steps(1); + } + + harness.event(Event::PointerButton { pos: to, button, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// The divider's x position: the 3D view ends 1 point left of it +fn divider_x(harness: &Harness<'_, TextureCraftApp>) -> f32 { + harness.state().viewport_rect.right() + 1.0 +} + +/// Allocated tiles in the selected layer's base color +fn painted_tiles(harness: &Harness<'_, TextureCraftApp>) -> usize { + let session = &harness.state().session; + let layer = session.selected_layer().expect("a selected layer"); + session.doc.pixels.layer(layer, Channel::BaseColor).map_or(0, |image| image.allocated_count()) +} + +/// The 2D view's texture as drawn: its centre's offset from the view's centre and its half width and height, in pixels at 1 point per pixel +fn uv_texture_on_screen(harness: &Harness<'_, TextureCraftApp>, views_right: f32) -> [f32; 4] { + let app = harness.state(); + + // egui draws the view's frame into its rect rounded to whole pixels + let width = views_right.round() - (divider_x(harness) + 1.0).round(); + let height = app.viewport_rect.bottom().round() - app.viewport_rect.top().round(); + let texture_size = app.session.doc.project.texture_sets[app.session.ts()].size(); + let [scale_x, scale_y] = texturecraft_render::uv_view_scale(width / height, app.ui.uv_zoom, texture_size); + let [pan_x, pan_y] = app.ui.uv_pan; + [pan_x * width * 0.5, pan_y * height * 0.5, scale_x * width * 0.5, scale_y * height * 0.5] +} + +/// The 3D camera's yaw and pitch +fn camera_angles(harness: &Harness<'_, TextureCraftApp>) -> (f32, f32) { + let camera = &harness.state().session.camera; + (camera.yaw, camera.pitch) +} + +#[test] +fn dragging_the_divider_resizes_the_views_within_their_minimum_width() { + let mut harness = split_app(); + let views_left = harness.state().viewport_rect.left(); + let start_x = divider_x(&harness); + let views_width = (start_x - views_left) * 2.0; + let views_right = views_left + views_width; + let y = harness.state().viewport_rect.center().y; + assert_eq!(harness.state().ui.split_ratio, 0.5); + + drag(&mut harness, PointerButton::Primary, pos2(start_x, y), pos2(start_x - 200.0, y)); + assert!((divider_x(&harness) - (start_x - 200.0)).abs() < 0.5, "follows the pointer: {}", divider_x(&harness)); + assert!((harness.state().ui.split_ratio - (start_x - 200.0 - views_left) / views_width).abs() < 1e-3); + + let x = divider_x(&harness); + drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(views_left + 10.0, y)); + assert!((divider_x(&harness) - views_left - MIN_VIEW_WIDTH).abs() < 0.5, "clamped on the left: {}", divider_x(&harness)); + + let x = divider_x(&harness); + drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(views_right - 10.0, y)); + assert!((views_right - divider_x(&harness) - MIN_VIEW_WIDTH).abs() < 0.5, "clamped on the right: {}", divider_x(&harness)); +} + +#[test] +fn pressing_on_the_divider_neither_paints_nor_moves_the_camera() { + let mut harness = split_app(); + + // Pan the texture's centre under the divider so a press there would paint if the 2D view got it + harness.state_mut().ui.uv_pan[0] = -1.0; + harness.run_steps(2); + let x = divider_x(&harness); + let y = harness.state().viewport_rect.center().y; + let (tiles, angles) = (painted_tiles(&harness), camera_angles(&harness)); + + harness.hover_at(pos2(x, y)); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: pos2(x, y), button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.event(Event::PointerButton { pos: pos2(x, y), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(x, y + 120.0)); + drag(&mut harness, PointerButton::Secondary, pos2(x, y), pos2(x + 120.0, y)); + assert_eq!(painted_tiles(&harness), tiles, "nothing painted"); + assert_eq!(camera_angles(&harness), angles, "no orbit"); + assert_eq!(divider_x(&harness), x, "a vertical or right-button drag leaves the divider in place"); + + // Beside the divider the views get the same input again + drag(&mut harness, PointerButton::Primary, pos2(x + BESIDE_DIVIDER, y), pos2(x + BESIDE_DIVIDER, y + 40.0)); + assert!(painted_tiles(&harness) > tiles, "the 2D view paints"); + drag(&mut harness, PointerButton::Secondary, pos2(x - BESIDE_DIVIDER, y), pos2(x - BESIDE_DIVIDER - 120.0, y)); + assert_ne!(camera_angles(&harness), angles, "the 3D view orbits"); +} + +#[test] +fn the_divider_position_survives_a_restart_and_old_saved_states_load_centred() { + let mut storage = MemoryStorage::default(); + let mut ui_state = UiState::default(); + ui_state.split_ratio = 0.3; + eframe::set_value(&mut storage, "ui", &ui_state); + let restored = eframe::get_value::(&storage, "ui").expect("saved state loads"); + assert_eq!(restored.split_ratio, 0.3); + + // A state saved before the divider existed has no ratio + let saved = storage.0.get("ui").cloned().unwrap(); + let without_ratio = saved.replace("split_ratio:0.3,", ""); + assert_ne!(without_ratio, saved, "the saved state names the ratio: {saved}"); + storage.0.insert("ui".to_owned(), without_ratio); + let restored = eframe::get_value::(&storage, "ui").expect("an older saved state loads"); + assert_eq!(restored.split_ratio, 0.5); +} + +#[test] +fn dragging_the_divider_keeps_the_uv_texture_size_and_offset_on_screen() { + // Zoomed in, a 2D sliver needs a zoom far past the one the view starts with + for zoom in [1.0, 4.0] { + let mut harness = split_app(); + harness.state_mut().ui.uv_zoom = zoom; + harness.state_mut().ui.uv_pan = [0.2, 0.1]; + harness.run_steps(2); + // The split starts centred, so the views end as far right of the divider as they start left of it + let views_left = harness.state().viewport_rect.left(); + let views_right = views_left + (divider_x(&harness) - views_left) * 2.0; + let y = harness.state().viewport_rect.center().y; + let before = uv_texture_on_screen(&harness, views_right); + + let assert_unchanged = |harness: &Harness<'_, TextureCraftApp>| { + let after = uv_texture_on_screen(harness, views_right); + for (was, is) in before.iter().zip(after) { + assert!((was - is).abs() < 0.5, "zoom {zoom}, divider at {}: {before:?} became {after:?}", divider_x(harness)); + } + }; + + for to in [views_left + 300.0, views_right - 150.0, views_right - 10.0, views_left + 500.0] { + let x = divider_x(&harness); + drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(to, y)); + assert_unchanged(&harness); + } + + // A slow drag past the right end, checked every frame for a nudge at the pixel rounding or the stop + let from = pos2(divider_x(&harness), y); + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + let mut pointer_x = from.x; + while pointer_x < views_right + 20.0 { + // Not a whole number of pixels, so the divider lands at every kind of rounding + pointer_x += 3.3; + harness.hover_at(pos2(pointer_x, y)); + harness.run_steps(1); + assert_unchanged(&harness); + } + harness.event(Event::PointerButton { pos: pos2(pointer_x, y), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert_unchanged(&harness); + + // Inside the wheel's 0.1 to 40 range, so the next scroll in the narrow view can't snap the zoom + let stopped_zoom = harness.state().ui.uv_zoom; + assert!((0.1..=40.0).contains(&stopped_zoom), "zoom {zoom} stopped at {stopped_zoom}"); + } +} From 23a752156cf29c0afef624e5373dadee74b41d55 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 09:47:51 +0000 Subject: [PATCH 10/73] UI: view layout and projection dropdowns in the top bar The 3D/2D, 3D-only and 2D-only buttons become one dropdown showing the current layout's icon, with the same commands and F1-F3 shortcuts. Beside it, a Perspective / Orthographic dropdown sets the camera through camera.set, so orthographic no longer hides in the Display Settings panel. Both use a new icon button with a caret, sharing the icon button style, and the bar's overflow width counts them. Test: picking a layout and Orthographic from the menus sets ui.layout and camera.ortho, and a second click on a dropdown closes its menu. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/toolbar.rs | 86 +++++++++++++++++++++++++----- crates/ui-egui/src/widgets.rs | 43 ++++++++++++--- crates/ui-egui/tests/toolbar.rs | 27 +++++++++- 12 files changed, 144 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 6ef517e9..89626724 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -556,6 +556,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "مدار"), ("Orthographic", "متوازي (إملائي)"), + ("Perspective", "منظوري"), ("Output directory", "دليل الإخراج"), ("Output high", "المخرج العالي"), ("Output low", "المخرج المنخفض"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index caaabb14..581cfc2b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -589,6 +589,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbit"), ("Orthographic", "Orthografisch"), + ("Perspective", "Perspektivisch"), ("Output directory", "Ausgabeverzeichnis"), ("Output high", "Ausgabe hoch"), ("Output low", "Ausgabe tief"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 6c8ccccb..2543cf6e 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -580,6 +580,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbitar"), ("Orthographic", "Ortográfica"), + ("Perspective", "Perspectiva"), ("Output directory", "Directorio de salida"), ("Output high", "Salida alta"), ("Output low", "Salida baja"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f10bba8d..66093168 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -595,6 +595,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbite"), ("Orthographic", "Orthographique"), + ("Perspective", "Perspective"), ("Output directory", "Dossier de sortie"), ("Output high", "Sortie haute"), ("Output low", "Sortie basse"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1c19d597..6766d794 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -586,6 +586,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbita"), ("Orthographic", "Ortografica"), + ("Perspective", "Prospettica"), ("Output directory", "Cartella di output"), ("Output high", "Output alto"), ("Output low", "Output basso"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 068603b5..41bd24a1 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -574,6 +574,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "オービット"), ("Orthographic", "平行投影"), + ("Perspective", "透視投影"), ("Output directory", "出力先フォルダー"), ("Output high", "出力の上限"), ("Output low", "出力の下限"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 137d6177..62548c58 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -565,6 +565,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "궤도 회전"), ("Orthographic", "직교"), + ("Perspective", "원근"), ("Output directory", "출력 디렉터리"), ("Output high", "출력 상한"), ("Output low", "출력 하한"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 99627b25..dc86a021 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -577,6 +577,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbitar"), ("Orthographic", "Ortográfica"), + ("Perspective", "Perspectiva"), ("Output directory", "Pasta de saída"), ("Output high", "Saída alta"), ("Output low", "Saída baixa"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 18623ce3..961a09e5 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -520,6 +520,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "环绕"), ("Orthographic", "正交"), + ("Perspective", "透视"), ("Output directory", "输出目录"), ("Output high", "输出高"), ("Output low", "输出低"), diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index b2e4d83e..897d305f 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -8,10 +8,10 @@ use texturecraft_engine::Tool; use crate::TextureCraftApp; use crate::docking::Panel; use crate::i18n::{tr, trf}; -use crate::keymap::tip; +use crate::keymap::{shortcut_of, tip}; use crate::state::{Mode, ViewLayout}; use crate::theme::{GUTTER, Tokens, card}; -use crate::widgets::{bar_slider, icon_button, icon_button_without_tooltip}; +use crate::widgets::{bar_slider, icon_button, icon_button_without_tooltip, icon_dropdown_button, icon_dropdown_button_width}; const BAR_SPACING: f32 = 10.0; const COMPACT_BAR_SPACING: f32 = 4.0; @@ -65,9 +65,10 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { }); } +/// Width of `view_buttons`, so the bar knows when to move them into the scrolling strip fn view_buttons_width(button_size: f32, spacing: f32) -> f32 { - // Five icons, two separators and the six gaps between them - 5.0 * button_size + 2.0 * BAR_SEPARATOR_WIDTH + 6.0 * spacing + // Two icons, two dropdowns, two separators and the five gaps between them + 2.0 * button_size + 2.0 * icon_dropdown_button_width(button_size) + 2.0 * BAR_SEPARATOR_WIDTH + 5.0 * spacing } /// View buttons in a right-to-left layout, with the screenshot button at the end @@ -78,15 +79,8 @@ fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); - for (layout, icon, label, command) in [ - (ViewLayout::Only2D, ic::SQUARE, "2D view only", "ui.layout.2d"), - (ViewLayout::Only3D, ic::CUBE, "3D view only", "ui.layout.3d"), - (ViewLayout::Split, ic::COLUMNS, "3D/2D views", "ui.layout.split"), - ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, tr(label), command), app.ui.layout == layout, button_size).clicked() { - crate::menus::invoke(app, &ui.ctx().clone(), command); - } - } + projection_dropdown(app, ui); + layout_dropdown(app, ui); ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; @@ -96,6 +90,72 @@ fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } } +/// The 3D/2D, 3D-only and 2D-only layouts, showing the current one's icon +fn layout_dropdown(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + const LAYOUTS: [(ViewLayout, &str, &str, &str); 3] = [ + (ViewLayout::Split, ic::SQUARE_SPLIT_HORIZONTAL, "3D/2D views", "ui.layout.split"), + (ViewLayout::Only3D, ic::SPHERE, "3D view only", "ui.layout.3d"), + (ViewLayout::Only2D, ic::SQUARE, "2D view only", "ui.layout.2d"), + ]; + + let (_, icon, label, command) = LAYOUTS.iter().find(|(layout, ..)| *layout == app.ui.layout).unwrap_or(&LAYOUTS[0]); + let tooltip = tip(&app.ui.keymap, tr(label), command); + let mut chosen = None; + icon_dropdown(ui, "view_layout", icon, &tooltip, |ui| { + for (layout, icon, label, command) in LAYOUTS { + if dropdown_row(ui, icon, tr(label), shortcut_of(&app.ui.keymap, command), app.ui.layout == layout) { + chosen = Some(command); + } + } + }); + + if let Some(command) = chosen { + crate::menus::invoke(app, &ui.ctx().clone(), command); + } +} + +/// Perspective or orthographic projection, the same setting as the Display Settings checkbox +fn projection_dropdown(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let projections = [(false, ic::PERSPECTIVE, tr("Perspective")), (true, ic::CUBE, tr("Orthographic"))]; + let ortho = app.session.camera.ortho; + let (_, icon, label) = projections.iter().find(|(choice, ..)| *choice == ortho).unwrap_or(&projections[0]); + let mut chosen = None; + icon_dropdown(ui, "view_projection", icon, label, |ui| { + for (choice, icon, label) in projections { + if dropdown_row(ui, icon, label, None, ortho == choice) { + chosen = Some(choice); + } + } + }); + + if let Some(choice) = chosen.filter(|choice| *choice != ortho) { + app.run("camera.set", json!({"ortho": choice})); + } +} + +/// An icon button with a caret that opens `menu` below it, highlighted while open +fn icon_dropdown(ui: &mut egui::Ui, id_salt: &str, icon: &str, tooltip: &str, menu: impl FnOnce(&mut egui::Ui)) { + let button_size = ui.spacing().interact_size.y; + let popup_id = ui.make_persistent_id(id_salt); + let open = egui::Popup::is_id_open(ui.ctx(), popup_id); + let mut response = icon_dropdown_button(ui, icon, tooltip, open, button_size); + if !open { + response = response.on_hover_text(tooltip); + } + + egui::Popup::menu(&response).id(popup_id).show(menu); +} + +/// One dropdown entry: icon, label and shortcut. Returns true when clicked +fn dropdown_row(ui: &mut egui::Ui, icon: &str, label: &str, shortcut: Option<&str>, selected: bool) -> bool { + let mut button = egui::Button::new(format!("{icon} {label}")).selected(selected); + if let Some(shortcut) = shortcut { + button = button.shortcut_text(shortcut); + } + + ui.add(button).clicked() +} + /// Scroll tool controls and, in narrow viewports, the view buttons fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, scroll_views: bool) { let button_size = ui.spacing().interact_size.y; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 72853550..79aa7eab 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -179,22 +179,51 @@ pub fn icon_button(ui: &mut Ui, icon: &str, tooltip: &str, selected: bool, size: icon_button_without_tooltip(ui, icon, tooltip, selected, size).on_hover_text(tooltip) } +/// Icon glyph size as a fraction of the button height +const ICON_SCALE: f32 = 0.62; + +/// Extra width an `icon_dropdown_button` gives its caret, as a fraction of the button height +const CARET_STRIP_SCALE: f32 = 0.34; + /// An `icon_button` with no tooltip, whose `label` still names it for screen readers pub fn icon_button_without_tooltip(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { - let tokens = Tokens::get(ui.ctx()); + let style = icon_button_style(&Tokens::get(ui.ctx())); + IconButton::new(label, vec2(size, size), &style).selected(selected).show(ui, |ui, rect, color| { + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * ICON_SCALE), color); + }) +} + +/// Width of an `icon_dropdown_button` `size` high: the square icon and the caret strip after it +pub fn icon_dropdown_button_width(size: f32) -> f32 { + size * (1.0 + CARET_STRIP_SCALE) +} + +/// An `icon_button_without_tooltip` with a dropdown caret after the icon, drawn in the icon's color +pub fn icon_dropdown_button(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { + // Caret glyph size, and how far its center sits from the right edge, as fractions of the height + const CARET_SCALE: f32 = 0.34; + const CARET_INSET_SCALE: f32 = 0.25; + + let style = icon_button_style(&Tokens::get(ui.ctx())); + IconButton::new(label, vec2(icon_dropdown_button_width(size), size), &style).selected(selected).show(ui, |ui, rect, color| { + let icon_center = rect.left_center() + vec2(size / 2.0, 0.0); + let caret_center = rect.right_center() - vec2(size * CARET_INSET_SCALE, 0.0); + ui.painter().text(icon_center, egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * ICON_SCALE), color); + ui.painter().text(caret_center, egui::Align2::CENTER_CENTER, egui_phosphor::regular::CARET_DOWN, egui::FontId::proportional(size * CARET_SCALE), color); + }) +} + +/// Transparent at rest, a hover well, and the active-tool well when pressed or selected +fn icon_button_style(tokens: &Tokens) -> IconButtonStyle { let well = |fill, icon| ButtonVisuals { fill, stroke: Stroke::NONE, icon }; - let style = IconButtonStyle { + IconButtonStyle { normal: well(Color32::TRANSPARENT, tokens.text), hovered: well(tokens.row_hover, tokens.text_strong), pressed: Some(well(tokens.tool_active, tokens.text_strong)), selected: well(tokens.tool_active, tokens.text_strong), corner_radius: CornerRadius::same(6), focus_stroke: Stroke::new(1.0, tokens.accent), - }; - - IconButton::new(label, vec2(size, size), &style).selected(selected).show(ui, |ui, rect, color| { - ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * 0.62), color); - }) + } } /// A flat button filled with the accent, white lettering (a dialog's main action). diff --git a/crates/ui-egui/tests/toolbar.rs b/crates/ui-egui/tests/toolbar.rs index 76b0053d..7d91e558 100644 --- a/crates/ui-egui/tests/toolbar.rs +++ b/crates/ui-egui/tests/toolbar.rs @@ -3,7 +3,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use texturecraft_engine::{Session, Tool}; -use texturecraft_ui_egui::state::Mode; +use texturecraft_ui_egui::state::{Mode, ViewLayout}; use texturecraft_ui_egui::{TextureCraftApp, theme, toolbar}; fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> { @@ -146,6 +146,31 @@ fn mode_buttons_keep_their_order_and_dispatch_commands() { } } +#[test] +fn view_dropdowns_set_the_layout_and_projection() { + let mut harness = toolbar_harness(1600.0, Tool::Paint); + harness.get_by_label("3D/2D views (F1)").click(); + harness.run_steps(3); + harness.get_by_label_contains("3D view only").click(); + harness.run_steps(3); + assert_eq!(harness.state().ui.layout, ViewLayout::Only3D); + assert!(harness.query_by_label_contains("2D view only").is_none(), "the layout menu stays open"); + assert!(harness.query_by_label("3D view only (F2)").is_some()); + + harness.get_by_label("Perspective").click(); + harness.run_steps(3); + harness.get_by_label("Perspective").click(); + harness.run_steps(3); + assert!(harness.query_by_label_contains("Orthographic").is_none(), "a second click keeps the projection menu open"); + + harness.get_by_label("Perspective").click(); + harness.run_steps(3); + harness.get_by_label_contains("Orthographic").click(); + harness.run_steps(3); + assert!(harness.state().session.camera.ortho); + assert!(harness.query_by_label("Orthographic").is_some()); +} + #[test] #[ignore] fn toolbar_frame_timing() { From 169221ea4c0e1f1b3fd70d97c6822713eefaa77c Mon Sep 17 00:00:00 2001 From: Agapenor <120006055+Agapenordev@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:30:59 +0000 Subject: [PATCH 11/73] Mark reimported projects as modified Mark successfully reimported projects as modified so closing them prompts to save. Keep failed reimports atomic and add saved-project regression coverage. Thanks @Agapenordev for the fix and regression test. --- crates/engine/src/file_cmds.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 48d4e8b2..0744aca2 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -448,6 +448,7 @@ impl Session { let mut next = Session::new(doc, mesh, source)?; next.log.extend(warnings); next.path = self.path.clone(); + next.modified = true; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); self.switch_to(next); Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n }))) @@ -610,6 +611,16 @@ fn close(s: &mut Session, _: &Value) -> Result { mod tests { use super::*; + #[test] + fn reimporting_a_saved_project_marks_it_modified() { + let obj = b"v -1 -1 0\nv 1 -1 0\nv 1 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nf 1/1 2/2 3/3\n"; + let original = Session::from_mesh_bytes("mesh.obj", obj, 128, "mesh").unwrap(); + let mut saved = Session::from_project_bytes(&original.to_project_bytes().unwrap()).unwrap(); + assert!(!saved.modified); + crate::execute(&mut saved, "file.reimportMesh", &Value::Null).unwrap(); + assert!(saved.modified, "reimport must trigger the unsaved-changes prompt"); + } + #[test] fn export_mesh_writes_obj_by_default_and_textured_glb() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); From adcc43b077ecf61d0e6c6541ace51d220ae9fa42 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 20:44:48 +0000 Subject: [PATCH 12/73] Smart mask previews that show the mask Shelf thumbnails now show each smart mask applied with mask.smart.apply to a baked preview shape (geom::primitives::preview_orb) and read back from the compositor (compose::mask_at, a sparse read sharing mask_image's per-tile code), shaded flat white over a softly lit near-black surface. The shape bakes once on a worker; preview::smart_mask's world-noise approximation is removed. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/eval.rs | 121 ++++++++++++++++-- crates/compose/src/lib.rs | 2 +- crates/engine/src/lib.rs | 2 + crates/engine/src/mask_preview.rs | 163 ++++++++++++++++++++++++ crates/engine/src/mask_preview_pixel.rs | 14 ++ crates/engine/src/preview.rs | 20 +-- crates/engine/src/session.rs | 7 + crates/geom/src/primitives.rs | 158 ++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/mask_previews.rs | 104 +++++++++++++++ crates/ui-egui/src/thumbs.rs | 30 +++-- 11 files changed, 579 insertions(+), 43 deletions(-) create mode 100644 crates/engine/src/mask_preview.rs create mode 100644 crates/engine/src/mask_preview_pixel.rs create mode 100644 crates/ui-egui/src/mask_previews.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 6c642b75..56b32cd8 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1843,31 +1843,25 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { let (w, h) = (inp.gbuf.width, inp.gbuf.height); let all = all_tiles(w, h); let fields = neighbourhood_fields(inp, &channels, &all); - let tiles: Vec<(u32, u32, Vec)> = all + let tiles: HashMap<(u32, u32), Vec> = all .par_iter() - .filter_map(|&(tx, ty)| { - let mp = mask_plan(inp, id, mask, tx, ty, Some(&fields))?; - let full = anchor_plan(inp, id, &channels, tx, ty, Some(&fields)); + .map(|&tile| { let mut buf = vec![0u8; TILE_AREA]; - for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { - let mut tex = Texel::new(inp, x, y, o, 0.0); - if !full.is_empty() { - tex.anchors_below(&full, id); - } + for (o, v) in mask_tile(inp, id, mask, &channels, &fields, tile, |_| true) { if let Some(b) = buf.get_mut(o) { - *b = (tex.mask(&mp) * 255.0 + 0.5) as u8; + *b = (v * 255.0 + 0.5) as u8; } } - Some((tx, ty, buf)) + (tile, buf) }) .collect(); + let size = size.max(1); let mut out = vec![0u8; (size * size) as usize]; - let lookup: std::collections::HashMap<(u32, u32), &Vec> = tiles.iter().map(|(x, y, b)| ((*x, *y), b)).collect(); for y in 0..size { for x in 0..size { let (sx, sy) = ((x as u64 * w as u64 / size as u64) as u32, (y as u64 * h as u64 / size as u64) as u32); - if let Some(t) = lookup.get(&(sx / TILE, sy / TILE)) + if let Some(t) = tiles.get(&(sx / TILE, sy / TILE)) && let Some(v) = t.get(((sy % TILE) * TILE + sx % TILE) as usize) && let Some(d) = out.get_mut((y * size + x) as usize) { @@ -1878,6 +1872,68 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { Some(out) } +/// The mask of layer `id` (0..=1) at `texels` (x, y) of the texture set, in order; 0 where the +/// mesh does not cover a texel. Only the requested texels are evaluated, so a sparse read (a +/// preview's visible texels) costs a fraction of [`mask_image`]. None when the layer has no +/// enabled mask. +pub fn mask_at(inp: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let mask = layer_mask(inp.project, id).filter(|m| m.enabled)?; + let channels = inp.project.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); + // Neighbourhood effects (blur, warp) read past the requested texels, so their fields cover + // every tile, as in `mask_image` + let fields = neighbourhood_fields(inp, &channels, &all_tiles(inp.gbuf.width, inp.gbuf.height)); + + // Per tile: offset in the tile -> indices in `texels` asking for it + let mut wanted: HashMap<(u32, u32), HashMap>> = HashMap::new(); + for (i, &(x, y)) in texels.iter().enumerate() { + let offset = ((y % TILE) * TILE + x % TILE) as usize; + wanted.entry((x / TILE, y / TILE)).or_default().entry(offset).or_default().push(i); + } + let values: Vec<(usize, f32)> = wanted + .par_iter() + .flat_map_iter(|(&tile, offsets)| { + mask_tile(inp, id, mask, &channels, &fields, tile, |o| offsets.contains_key(&o)) + .into_iter() + .flat_map(move |(o, v)| offsets.get(&o).into_iter().flatten().map(move |&i| (i, v))) + }) + .collect(); + + let mut out = vec![0.0; texels.len()]; + for (i, v) in values { + if let Some(d) = out.get_mut(i) { + *d = v; + } + } + Some(out) +} + +/// Layer `id`'s enabled `mask` at the covered texels of `tile` whose offset in the tile passes +/// `wanted`, as (offset, value 0..=1); empty for a tile the mask has no plan for. +fn mask_tile( + inp: &Inputs, + id: LayerId, + mask: &Mask, + channels: &[Channel], + fields: &Fields, + (tx, ty): (u32, u32), + wanted: impl Fn(usize) -> bool, +) -> Vec<(usize, f32)> { + let Some(plan) = mask_plan(inp, id, mask, tx, ty, Some(fields)) else { return Vec::new() }; + + // Masks that read anchor points need the stack below the layer + let full = anchor_plan(inp, id, channels, tx, ty, Some(fields)); + tile_texels(inp.gbuf, tx, ty) + .filter(|&(_, _, o)| wanted(o)) + .map(|(x, y, o)| { + let mut texel = Texel::new(inp, x, y, o, 0.0); + if !full.is_empty() { + texel.anchors_below(&full, id); + } + (o, texel.mask(&plan)) + }) + .collect() +} + /// Tiles [`effect_histogram`] samples at most (a million texels). const HISTOGRAM_TILES: usize = 256; @@ -2175,6 +2231,45 @@ mod tests { assert!(vals.iter().any(|v| *v > 0.99) && vals.iter().any(|v| *v < 0.51), "{vals:?}"); } + #[test] + fn mask_at_reads_the_same_values_as_the_mask_image() { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [1.0, 1.0, 1.0], 1.0); + let eid = f.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + let pattern = Procedural::new(ProceduralKind::Checker); + mask.effects.push(Effect::new( + eid, + EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() }, + )); + f.project.layer_mut(id).unwrap().mask = Some(mask); + let maskless = f.project.alloc_id(); + let images = Default::default(); + let inp = Inputs { + project: &f.project, + ts: 0, + mesh: &f.mesh, + gbuf: &f.gbuf, + pixels: &f.pixels, + baked: &f.baked, + preview: None, + images: &images, + bounds: f.mesh.bounds(), + }; + + // Scattered texels, one twice, one outside the texture + let texels = [(0, 0), (13, 20), (63, 63), (40, 7), (13, 20), (64, 64)]; + let sparse = mask_at(&inp, id, &texels).unwrap(); + let image = mask_image(&inp, id, 64).unwrap(); + for (&(x, y), v) in texels.iter().zip(&sparse).take(5) { + let expected = f32::from(image[(y * 64 + x) as usize]) / 255.0; + assert!((v - expected).abs() <= 0.5 / 255.0 + 1e-6, "({x}, {y}): {v} vs {expected}"); + } + assert_eq!(sparse[5], 0.0, "uncovered texels read 0"); + assert!(sparse.iter().any(|v| *v > 0.99) && sparse.iter().take(5).any(|v| *v < 0.01), "{sparse:?}"); + assert!(mask_at(&inp, maskless, &texels).is_none(), "no mask, no values"); + } + #[test] fn blur_filter_softens_mask_edges() { let mut f = fixture(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5e34945c..ee940e06 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -17,6 +17,6 @@ pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, - mask_image, pad_tiles, + mask_at, mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ed07d645..ca7cdeea 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -25,6 +25,8 @@ pub mod layer_cmds; pub mod layer_ops; pub mod link_cmds; pub mod mask_cmds; +pub mod mask_preview; +mod mask_preview_pixel; pub mod material_lib; pub mod materials; pub mod materialx_cmds; diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs new file mode 100644 index 00000000..e7116d9d --- /dev/null +++ b/crates/engine/src/mask_preview.rs @@ -0,0 +1,163 @@ +//! Smart mask shelf previews: the real smart masks on a baked preview shape. The shape +//! ([`primitives::preview_orb`]) is baked once; each preset is then applied with +//! `mask.smart.apply`, read back from the compositor and seen from a fixed camera. + +use serde_json::json; +use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; +use texturecraft_geom::glam::{Quat, Vec2, Vec3}; +use texturecraft_geom::{primitives, surface_at}; + +pub use crate::mask_preview_pixel::MaskPreviewPixel; +use crate::{EngineError, Result, Session}; + +/// Texture and bake size of the preview shape in texels (at 256 the edge lines break up). +const TEXTURE_PX: u32 = 512; +/// Camera rays per thumbnail pixel along each axis (anti-aliased outline). +const SUPERSAMPLE: usize = 2; +/// AO and thickness rays per texel (the default is 64; fewer look the same at thumbnail size). +const OCCLUSION_RAYS: u32 = 12; +/// Mesh curvature rays per texel (the default is 32; fewer look the same at thumbnail size). +const CURVATURE_RAYS: u32 = 12; +/// Mesh curvature sampling radius relative to the bounding box: wide enough that edges read as +/// lines at thumbnail size, narrow enough that the round body does not count as an edge. +const CURVATURE_RADIUS: f32 = 0.005; +/// The mesh maps the smart mask generators read. +const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; +/// Camera: looking down by this angle, turned to show the front, left and top panels. +const CAMERA_PITCH_DEG: f32 = 35.0; +const CAMERA_YAW_DEG: f32 = -34.4; + +/// What one camera sub-pixel sees: the index of its texel in the preview's texel list and the +/// view-space normal there (None where the ray misses). +type CameraSample = Option<(usize, Vec3)>; + +/// The baked preview shape and what each thumbnail sub-pixel sees. +pub struct MaskPreview { + session: Session, + layer: LayerId, + size: usize, + /// The texels (x, y) the camera sees, each once. + texels: Vec<(u32, u32)>, + /// Per sub-pixel, row-major `(size · SUPERSAMPLE)²`. + samples: Vec, +} + +impl MaskPreview { + /// Bake the preview shape once and aim the camera for `size²` thumbnails. + pub fn new(size: usize) -> Result { + let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; + let set = session.doc.project.texture_set_mut(0)?; + set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; + set.bake.high_poly.use_low_as_high = true; + set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; + set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; + set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; + set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; + set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; + for map in BakedMap::ALL { + set.bake.maps.set_enabled(map, MAPS.contains(&map)); + } + let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; + session.bake_now(0, false)?; + + let (texels, samples) = camera_samples(&session, size * SUPERSAMPLE); + Ok(MaskPreview { session, layer, size, texels, samples }) + } + + /// Smart mask `id` per thumbnail pixel, row-major `size²`, None where the shape is not seen + /// (None for an unknown id). + pub fn render(&mut self, id: &str) -> Option>> { + crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; + // Nothing is undone here; the snapshots would pile up over the presets + self.session.undo.clear(); + let values = self.session.mask_at(self.layer, &self.texels)?; + + let fine = self.size * SUPERSAMPLE; + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..self.size * self.size) + .map(|i| { + let (x, y) = (i % self.size, i / self.size); + let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0); + for sy in 0..SUPERSAMPLE { + for sx in 0..SUPERSAMPLE { + let Some(&Some((texel, n))) = self.samples.get((y * SUPERSAMPLE + sy) * fine + x * SUPERSAMPLE + sx) else { continue }; + + mask += values.get(texel).copied().unwrap_or(0.0); + normal += n; + hits += 1.0; + } + } + (hits > 0.0).then(|| MaskPreviewPixel { mask: mask / hits, normal: normal.normalize_or_zero(), coverage: hits / sub_pixels }) + }) + .collect(); + Some(pixels) + } +} + +/// What each pixel of a `size²` orthographic view of the shape sees: the distinct texels hit, and +/// per pixel (row-major) its sample. +fn camera_samples(session: &Session, size: usize) -> (Vec<(u32, u32)>, Vec) { + let (lo, hi) = session.mesh.bounds(); + let center = (lo + hi) * 0.5; + let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); + let pitch = CAMERA_PITCH_DEG.to_radians(); + let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); + let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); + let right = turn * Vec3::X; + let up = right.cross(forward); + let max_texel = TEXTURE_PX - 1; + + let mut texels = Vec::new(); + let mut index_of = std::collections::HashMap::new(); + let samples = (0..size * size) + .map(|i| { + let ndc = Vec2::new(((i % size) as f32 + 0.5) / size as f32 * 2.0 - 1.0, 1.0 - ((i / size) as f32 + 0.5) / size as f32 * 2.0); + // Start well outside the shape so every ray enters it from the front + let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; + let hit = session.bvh.closest(origin, forward, radius * 8.0)?; + let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; + let texel = (((surface.uv.x * TEXTURE_PX as f32) as u32).min(max_texel), ((surface.uv.y * TEXTURE_PX as f32) as u32).min(max_texel)); + let index = *index_of.entry(texel).or_insert_with(|| { + texels.push(texel); + texels.len() - 1 + }); + let n = surface.nrm; + Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) + }) + .collect(); + (texels, samples) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Mean absolute difference of the masks of two previews over the pixels both see. + fn difference(a: &[Option], b: &[Option]) -> f32 { + let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); + pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 + } + + #[test] + fn smart_mask_previews_are_in_range_and_tell_edges_from_cavities() { + let size = 24; + let mut preview = MaskPreview::new(size).unwrap(); + for sm in crate::smart_masks::SMART_MASKS { + let px = preview.render(sm.id).unwrap_or_else(|| panic!("{}", sm.id)); + assert_eq!(px.len(), size * size, "{}", sm.id); + assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id); + let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect(); + assert!(seen.len() > size * size / 3, "{}: the shape fills the frame", sm.id); + for p in seen { + assert!((0.0..=1.0).contains(&p.mask) && (0.0..=1.0).contains(&p.coverage) && p.coverage > 0.0, "{}: {p:?}", sm.id); + assert!(p.normal.is_finite(), "{}: {p:?}", sm.id); + } + } + + let (edges, cavities) = (preview.render("edges_sharp").unwrap(), preview.render("dirt_cavities").unwrap()); + let shows = |px: &[Option]| px.iter().flatten().any(|p| p.mask > 0.5); + assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); + assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); + assert!(preview.render("nope").is_none()); + } +} diff --git a/crates/engine/src/mask_preview_pixel.rs b/crates/engine/src/mask_preview_pixel.rs new file mode 100644 index 00000000..bcde5629 --- /dev/null +++ b/crates/engine/src/mask_preview_pixel.rs @@ -0,0 +1,14 @@ +//! One pixel of a smart mask preview (see [`crate::mask_preview::MaskPreview`]). + +use texturecraft_geom::glam::Vec3; + +/// The smart mask value seen at a preview pixel, with what a display needs to shade the shape. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MaskPreviewPixel { + /// Mask value (0..=1). + pub mask: f32, + /// Surface normal in view space (+X right, +Y up, +Z towards the viewer). + pub normal: Vec3, + /// Fraction of the pixel the shape covers (0..=1, anti-aliased outline). + pub coverage: f32, +} diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 3c3aa130..1dc33631 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -1,6 +1,7 @@ -//! Shelf previews: built-in materials and smart masks evaluated on a unit sphere seen from +Z, -//! without a mesh or baked maps (generators that need mesh maps are approximated with world-space -//! noise). Cheap enough for lazily rendered thumbnails. +//! Shelf previews: built-in materials evaluated on a unit sphere seen from +Z, without a mesh or +//! baked maps (generators that need mesh maps are approximated with world-space noise), and +//! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked +//! preview ([`crate::mask_preview`]). use texturecraft_compose::pattern::{Coords, procedural, world_noise}; use texturecraft_core::{ @@ -183,13 +184,6 @@ pub fn filter(id: &str, size: usize) -> Option>> { ) } -/// Preview of smart mask `id`: the mask value per pixel (None for an unknown id). -pub fn smart_mask(id: &str, size: usize) -> Option>> { - let (bg, fx) = crate::smart_masks::preset(id)?; - let m = crate::smart_masks::build_mask(&mut Project::new("preview", ""), bg, fx); - Some(sphere_normals(size).map(|n| n.map(|n| mask(&m, &coords(n)))).collect()) -} - #[cfg(test)] mod tests { use super::*; @@ -202,11 +196,7 @@ mod tests { assert!(center.base.iter().chain([¢er.metallic, ¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", m.id); assert!(px[0].is_none(), "corners are outside the sphere"); } - for sm in crate::smart_masks::SMART_MASKS { - let px = smart_mask(sm.id, 16).unwrap_or_else(|| panic!("{}", sm.id)); - assert!(px.iter().flatten().all(|v| (0.0..=1.0).contains(v)), "{}", sm.id); - } - assert!(material("nope", 8).is_none() && smart_mask("nope", 8).is_none() && filter("nope", 8).is_none()); + assert!(material("nope", 8).is_none() && filter("nope", 8).is_none()); for f in crate::filter_lib::FILTERS { let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id)); let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id)); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 7ec12739..214bd69f 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -829,6 +829,13 @@ impl Session { Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect()) } + /// Layer `id`'s mask (0..=1) at `texels` (x, y) of its texture set, in order (None without a + /// mask); evaluates only those texels. + pub fn mask_at(&self, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let (ts, _, _) = self.doc.project.locate(id)?; + self.with_inputs(ts, |inp| texturecraft_compose::mask_at(inp, id, texels)) + } + /// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's /// mask, or for a content effect the layer's `channel` (None for an unknown effect). pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option> { diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs index 6403faed..29bad947 100644 --- a/crates/geom/src/primitives.rs +++ b/crates/geom/src/primitives.rs @@ -63,9 +63,17 @@ impl Builder { } } + /// The mesh of one material, with tangents. fn finish(self, material: &str) -> Mesh { + let mut m = self.into_mesh(material); + m.compute_tangents(); + m + } + + /// The mesh of one material, without tangents. + fn into_mesh(self, material: &str) -> Mesh { let count = self.idx.len() as u32; - let mut m = Mesh { + Mesh { positions: self.p, normals: self.n, uvs: self.uv, @@ -75,9 +83,7 @@ impl Builder { submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], materials: vec![material.into()], diagonals: self.diag, - }; - m.compute_tangents(); - m + } } } @@ -189,6 +195,132 @@ fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize }); } +/// [`preview_orb`]: half-size of the cube that cuts the unit sphere flat (each face rim is the +/// circle where they meet). +const ORB_CUT: f32 = 0.8; +/// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius. +const ORB_PANEL_VALLEY: f32 = 0.88; + +/// The smart mask preview shape: a sphere cut flat by a cube on six sides, on a thin round base. +/// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly +/// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys +/// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it +/// meets the body) and plain rounded corners (gradients). Faces +Z (front), -X (left) and +Y (top) +/// carry the panels, so the shape is made to be seen from the front left, slightly from above. +/// The body takes the top 79 % of the UV square, the base the bottom 19 %. +pub fn preview_orb() -> Mesh { + // Grid rows (columns: twice as many); fewer blur the panel walls, more cost bake time + const ROWS: usize = 300; + const BODY_UV_HEIGHT: f32 = 0.79; + const BASE_UV: UvRect = UvRect { o: Vec2::new(0.0, 0.81), s: Vec2::new(1.0, 0.19) }; + const BASE_RADIUS: f32 = 0.95; + const BASE_HALF_HEIGHT: f32 = 0.025; + const BASE_Y: f32 = -0.6; + const BASE_RIM_STEPS: usize = 12; + const BASE_SEGMENTS: usize = 256; + + let mut b = Builder::default(); + b.grid(ROWS, ROWS * 2, |i, j| { + let (u, v) = (j as f32 / (ROWS * 2) as f32, i as f32 / ROWS as f32); + let (theta, phi) = (v * PI, u * TAU + PI * 1.5); + let dir = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()); + (dir * preview_orb_radius(dir), dir, Vec2::new(u, v * BODY_UV_HEIGHT)) + }); + + // Base: a thin disc with a rounded rim (a half circle from its top face to its bottom face) + let mut profile = vec![(0.0, BASE_HALF_HEIGHT)]; + for k in 0..=BASE_RIM_STEPS { + let a = k as f32 / BASE_RIM_STEPS as f32 * PI; + profile.push((BASE_RADIUS - BASE_HALF_HEIGHT + BASE_HALF_HEIGHT * a.sin(), BASE_HALF_HEIGHT * a.cos())); + } + profile.push((0.0, -BASE_HALF_HEIGHT)); + lathe_into(&mut b, Vec3::Y * BASE_Y, &profile, BASE_SEGMENTS, BASE_UV); + + let mut m = b.into_mesh("Preview"); + // Normals from the triangles: the panel walls are too steep for the sphere's directions + m.compute_normals(); + // Body and base both run U around the vertical axis, so the tangent is that direction (a + // fraction of the cost of the general tangent pass on this many triangles) + m.tangents = m + .positions + .iter() + .zip(&m.normals) + .map(|(p, n)| { + let around = Vec3::new(p.z, 0.0, -p.x).try_normalize().unwrap_or(Vec3::X); + (around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(1.0) + }) + .collect(); + m +} + +/// Distance from the centre of the [`preview_orb`] body along unit direction `d`. +fn preview_orb_radius(d: Vec3) -> f32 { + // Rim blends: the sharp faces, and the softly blended left face + const SHARP_BLEND: f32 = 0.035; + const SOFT_BLEND: f32 = 0.18; + // Domed panels: valley depth below the face, dome rise past it; the left panel is smaller + const PANEL_DEPTH: f32 = 0.11; + const PANEL_BULGE: f32 = 0.04; + const LEFT_PANEL_SCALE: f32 = 0.9; + // Slot around the middle: centre height, half-width, edge rounding, depth; it fades out over + // this fraction of the left panel's rim + const SLOT_Y: f32 = -0.03; + const SLOT_HALF_WIDTH: f32 = 0.05; + const SLOT_ROUNDING: f32 = 0.015; + const SLOT_DEPTH: f32 = 0.12; + const SLOT_FADE: f32 = 0.04; + + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let smooth = |a: f32, b: f32, x: f32| { + let t = ((x - a) / (b - a)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) + }; + // Polynomial smooth minimum with blend radius k + let smin = |a: f32, b: f32, k: f32| { + let h = (0.5 + 0.5 * (b - a) / k).clamp(0.0, 1.0); + b + (a - b) * h - k * h * (1.0 - h) + }; + // Domed panel at `rho` (radius in face units) inside a face of rim `rim`: a steep wall from + // the rim into a valley, then a dome rising slightly past the face over the middle + let panel = |rho: f32, rim: f32| { + let valley = rim * ORB_PANEL_VALLEY; + if rho < valley { + PANEL_BULGE - (PANEL_BULGE + PANEL_DEPTH) * (rho / valley).powi(3) + } else { + -PANEL_DEPTH * (1.0 - ((rho - valley) / (rim - valley)).min(1.0)) + } + }; + let face_rho = |along: f32, u: f32, v: f32| (u * u + v * v).sqrt() / along.max(1e-3); + + // The cut: sharp rims except the softly blended left face + let mut radius = 1.0f32; + for (along, blend) in [(d.x, SHARP_BLEND), (-d.x, SOFT_BLEND), (d.y, SHARP_BLEND), (-d.y, SHARP_BLEND), (d.z, SHARP_BLEND), (-d.z, SHARP_BLEND)] { + // Directions facing away from a face stay on the sphere (9 = far past it) + let to_face = if along > 1e-3 { ORB_CUT / along } else { 9.0 }; + radius = smin(radius, to_face, blend); + } + + let a = d.abs(); + let left_rim = rim * LEFT_PANEL_SCALE; + let mut relief = 0.0; + if d.z > 0.0 && a.z >= a.x && a.z >= a.y { + relief += panel(face_rho(d.z, d.x, d.y), rim); + } + if d.x < 0.0 && a.x >= a.y && a.x >= a.z { + relief += panel(face_rho(-d.x, d.y, d.z), left_rim); + } + if d.y > 0.0 && a.y >= a.x && a.y >= a.z { + relief += panel(face_rho(d.y, d.x, d.z), rim); + } + + // Slot around the middle, stopping at the left panel + let in_left_panel = if d.x < 0.0 { 1.0 - smooth(left_rim * (1.0 - SLOT_FADE), left_rim * (1.0 + SLOT_FADE), face_rho(-d.x, d.y, d.z)) } else { 0.0 }; + let slot_band = 1.0 - smooth(SLOT_HALF_WIDTH - SLOT_ROUNDING, SLOT_HALF_WIDTH + SLOT_ROUNDING, (d.y - SLOT_Y).abs()); + relief -= SLOT_DEPTH * slot_band * (1.0 - in_left_panel); + + radius + relief +} + /// A flat disk facing up (+Y) or down, with planar UVs inside `r`. fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) { let n = if up { Vec3::Y } else { Vec3::NEG_Y }; @@ -340,6 +472,8 @@ pub fn builtin(id: &str) -> Option { "plane" => plane(2.0, 16), "crate" => crate_scene(), "udim_plane" | "udimplane" => udim_plane(), + // Not offered for new projects (not in BUILTINS): the smart mask preview session's mesh + "preview_orb" => preview_orb(), _ => return None, }) } @@ -396,6 +530,22 @@ mod tests { assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::>(), vec![(0, 0), (1, 0)]); } + #[test] + fn preview_orb_is_well_formed_with_domed_panels() { + let m = preview_orb(); + check(&m, 1.0); + + // Above the middle slot, the front panel's dome rises past the cut face and its valley + // sits below it + let front_depth = |rho: f32| { + let d = Vec3::new(0.0, rho, 1.0).normalize(); + preview_orb_radius(d) * d.z + }; + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let (dome, valley) = (front_depth(0.2), front_depth(rim * ORB_PANEL_VALLEY)); + assert!(dome > ORB_CUT && valley < ORB_CUT - 0.05, "dome {dome}, valley {valley}"); + } + #[test] fn material_ball_has_two_materials() { let m = material_ball(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8bfc66c9..3253a7a9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,6 +16,7 @@ pub mod fonts; pub mod gpu; pub mod i18n; pub mod keymap; +mod mask_previews; pub mod menus; pub mod parity; pub mod profile; diff --git a/crates/ui-egui/src/mask_previews.rs b/crates/ui-egui/src/mask_previews.rs new file mode 100644 index 00000000..fc6018e4 --- /dev/null +++ b/crates/ui-egui/src/mask_previews.rs @@ -0,0 +1,104 @@ +//! Smart mask shelf thumbnails: every smart mask on the baked preview shape, rendered together on +//! a worker the first time the shelf asks for one (baking the shape takes about two seconds on +//! the CPU; on the web the work runs inline). + +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::time::Duration; + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::mask_preview::{MaskPreview, MaskPreviewPixel}; +use texturecraft_engine::smart_masks::SMART_MASKS; +use texturecraft_engine::texel::linear_to_srgb; + +/// View-space directions of the key light (upper left) and a weaker fill (right), and how much +/// each lights the surface. +const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; +const FILL: [f32; 3] = [0.7, -0.1, 0.7]; +const AMBIENT: f32 = 0.1; +const KEY_STRENGTH: f32 = 0.8; +const FILL_STRENGTH: f32 = 0.35; +/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the +/// shape reads without looking glossy. +const UNMASKED_ALBEDO: f32 = 0.006; +const SHEEN: f32 = 0.1; +const SHEEN_EXPONENT: f32 = 40.0; +/// Where the mask is full: white, darkened at most this much where unlit. +const WHITE_SHADING: f32 = 0.2; +/// How often the shelf checks for the thumbnails while they render. +const POLL: Duration = Duration::from_millis(100); + +/// Smart mask thumbnails by id, as the worker sends them. +type Thumbnails = Vec<(&'static str, ColorImage)>; + +/// Where the smart mask thumbnails are. +#[derive(Default)] +pub enum MaskPreviews { + #[default] + NotStarted, + Rendering(Receiver), + /// Handed out (or the worker failed; the tiles keep their placeholder). + Finished, +} + +impl MaskPreviews { + /// Start rendering `size²` thumbnails on the first call; the finished thumbnails on the call + /// that finds them done (None before and after). + pub fn poll(&mut self, ctx: &egui::Context, size: usize) -> Option { + if matches!(self, MaskPreviews::NotStarted) { + *self = MaskPreviews::Rendering(crate::spawn_worker("texturecraft-mask-previews", move || render(size))); + } + let MaskPreviews::Rendering(rx) = self else { return None }; + + match rx.try_recv() { + Ok(thumbnails) => { + *self = MaskPreviews::Finished; + Some(thumbnails) + } + Err(TryRecvError::Empty) => { + ctx.request_repaint_after(POLL); + None + } + // The worker stopped without a result + Err(TryRecvError::Disconnected) => { + *self = MaskPreviews::Finished; + None + } + } + } +} + +/// Every smart mask's `size²` thumbnail (empty when the preview shape fails to bake). +fn render(size: usize) -> Thumbnails { + let mut preview = match MaskPreview::new(size) { + Ok(p) => p, + Err(e) => { + log::warn!("smart mask previews: {e}"); + return Vec::new(); + } + }; + SMART_MASKS.iter().filter_map(|m| Some((m.id, image(size, &preview.render(m.id)?)))).collect() +} + +/// A thumbnail (sRGB, transparent outside the shape) from preview pixels (row-major `size²`): +/// the mask as white over a near-black surface lit softly from the upper left. No environment +/// reflections. +fn image(size: usize, pixels: &[Option]) -> ColorImage { + let key = Vec3::from(KEY).normalize(); + let fill = Vec3::from(FILL).normalize(); + let half = (key + Vec3::Z).normalize(); + let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (out, p) in img.pixels.iter_mut().zip(pixels) { + let Some(p) = p else { continue }; + + let n = p.normal; + let shading = AMBIENT + KEY_STRENGTH * n.dot(key).max(0.0) + FILL_STRENGTH * n.dot(fill).max(0.0); + let unmasked = UNMASKED_ALBEDO * shading + SHEEN * n.dot(half).max(0.0).powf(SHEEN_EXPONENT); + let masked = 1.0 - WHITE_SHADING * (1.0 - shading.min(1.0)); + let linear = unmasked + (masked - unmasked) * p.mask.clamp(0.0, 1.0); + let gray = (linear_to_srgb(linear.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(gray, gray, gray, (p.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + } + img +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index a2d85712..f5590b31 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,6 +1,7 @@ -//! Thumbnails: shaded material spheres, smart mask spheres, procedural swatches and brush alpha -//! previews, rendered on the CPU into cached egui textures (no image assets). New shelf -//! thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a frame. +//! Thumbnails: shaded material spheres, smart masks on a baked preview shape, procedural swatches +//! and brush alpha previews, rendered on the CPU into cached egui textures (no image assets). New +//! shelf thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a +//! frame; the smart mask previews render together on a worker. use std::collections::HashMap; @@ -11,6 +12,8 @@ use texturecraft_engine::paint::{BrushAlpha, BrushSettings, Shape, alphas}; use texturecraft_engine::preview::{self, Sample}; use texturecraft_engine::texel::linear_to_srgb; +use crate::mask_previews::MaskPreviews; + /// Shelf thumbnails rendered per frame at most (the rest follow on the next frames). const PER_FRAME: usize = 2; /// Shelf sphere thumbnail size in pixels. @@ -24,6 +27,7 @@ pub struct Thumbs { images: HashMap, /// (frame, thumbnails rendered in it). budget: (u64, usize), + mask_previews: MaskPreviews, } fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { @@ -161,14 +165,20 @@ impl Thumbs { self.shelf(ctx, format!("mat:{id}"), || sphere_image(SPHERE_PX, &preview::material(id, SPHERE_PX).unwrap_or_default())) } - /// Sphere thumbnail of smart mask `id`: white where the mask applies, over dark gray. + /// Thumbnail of smart mask `id` on the baked preview shape (None while the thumbnails + /// render; they all arrive together). pub fn smart_mask(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("mask:{id}"), || { - let px = preview::smart_mask(id, SPHERE_PX).unwrap_or_default(); - let samples: Vec> = - px.iter().map(|m| m.map(|m| Sample { base: [0.04 + 0.76 * m; 3], metallic: 0.0, roughness: 0.6, height: 0.0 })).collect(); - sphere_image(SPHERE_PX, &samples) - }) + let key = format!("mask:{id}"); + if let Some(t) = self.shelf.get(&key) { + return Some(t.clone()); + } + + for (mask_id, image) in self.mask_previews.poll(ctx, SPHERE_PX).unwrap_or_default() { + let mask_key = format!("mask:{mask_id}"); + let t = ctx.load_texture(format!("thumb_{mask_key}"), image, TextureOptions::LINEAR); + self.shelf.insert(mask_key, t); + } + self.shelf.get(&key).cloned() } /// Sphere thumbnail of library filter `id` applied to a sample material. From 34ba091e8a2e6049ca50be177fcb21500ca01743 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 20:44:48 +0000 Subject: [PATCH 13/73] Smart mask previews that show the mask Shelf thumbnails now show each smart mask applied with mask.smart.apply to a baked preview shape (geom::primitives::preview_orb) and read back from the compositor (compose::mask_at, a sparse read sharing mask_image's per-tile code), shaded flat white over a softly lit near-black surface. The shape bakes once on a worker; preview::smart_mask's world-noise approximation is removed. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/eval.rs | 121 ++++++++++++++++-- crates/compose/src/lib.rs | 2 +- crates/engine/src/lib.rs | 2 + crates/engine/src/mask_preview.rs | 163 ++++++++++++++++++++++++ crates/engine/src/mask_preview_pixel.rs | 14 ++ crates/engine/src/preview.rs | 20 +-- crates/engine/src/session.rs | 7 + crates/geom/src/primitives.rs | 158 ++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/mask_previews.rs | 104 +++++++++++++++ crates/ui-egui/src/thumbs.rs | 30 +++-- 11 files changed, 579 insertions(+), 43 deletions(-) create mode 100644 crates/engine/src/mask_preview.rs create mode 100644 crates/engine/src/mask_preview_pixel.rs create mode 100644 crates/ui-egui/src/mask_previews.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 6c642b75..56b32cd8 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1843,31 +1843,25 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { let (w, h) = (inp.gbuf.width, inp.gbuf.height); let all = all_tiles(w, h); let fields = neighbourhood_fields(inp, &channels, &all); - let tiles: Vec<(u32, u32, Vec)> = all + let tiles: HashMap<(u32, u32), Vec> = all .par_iter() - .filter_map(|&(tx, ty)| { - let mp = mask_plan(inp, id, mask, tx, ty, Some(&fields))?; - let full = anchor_plan(inp, id, &channels, tx, ty, Some(&fields)); + .map(|&tile| { let mut buf = vec![0u8; TILE_AREA]; - for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { - let mut tex = Texel::new(inp, x, y, o, 0.0); - if !full.is_empty() { - tex.anchors_below(&full, id); - } + for (o, v) in mask_tile(inp, id, mask, &channels, &fields, tile, |_| true) { if let Some(b) = buf.get_mut(o) { - *b = (tex.mask(&mp) * 255.0 + 0.5) as u8; + *b = (v * 255.0 + 0.5) as u8; } } - Some((tx, ty, buf)) + (tile, buf) }) .collect(); + let size = size.max(1); let mut out = vec![0u8; (size * size) as usize]; - let lookup: std::collections::HashMap<(u32, u32), &Vec> = tiles.iter().map(|(x, y, b)| ((*x, *y), b)).collect(); for y in 0..size { for x in 0..size { let (sx, sy) = ((x as u64 * w as u64 / size as u64) as u32, (y as u64 * h as u64 / size as u64) as u32); - if let Some(t) = lookup.get(&(sx / TILE, sy / TILE)) + if let Some(t) = tiles.get(&(sx / TILE, sy / TILE)) && let Some(v) = t.get(((sy % TILE) * TILE + sx % TILE) as usize) && let Some(d) = out.get_mut((y * size + x) as usize) { @@ -1878,6 +1872,68 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { Some(out) } +/// The mask of layer `id` (0..=1) at `texels` (x, y) of the texture set, in order; 0 where the +/// mesh does not cover a texel. Only the requested texels are evaluated, so a sparse read (a +/// preview's visible texels) costs a fraction of [`mask_image`]. None when the layer has no +/// enabled mask. +pub fn mask_at(inp: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let mask = layer_mask(inp.project, id).filter(|m| m.enabled)?; + let channels = inp.project.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); + // Neighbourhood effects (blur, warp) read past the requested texels, so their fields cover + // every tile, as in `mask_image` + let fields = neighbourhood_fields(inp, &channels, &all_tiles(inp.gbuf.width, inp.gbuf.height)); + + // Per tile: offset in the tile -> indices in `texels` asking for it + let mut wanted: HashMap<(u32, u32), HashMap>> = HashMap::new(); + for (i, &(x, y)) in texels.iter().enumerate() { + let offset = ((y % TILE) * TILE + x % TILE) as usize; + wanted.entry((x / TILE, y / TILE)).or_default().entry(offset).or_default().push(i); + } + let values: Vec<(usize, f32)> = wanted + .par_iter() + .flat_map_iter(|(&tile, offsets)| { + mask_tile(inp, id, mask, &channels, &fields, tile, |o| offsets.contains_key(&o)) + .into_iter() + .flat_map(move |(o, v)| offsets.get(&o).into_iter().flatten().map(move |&i| (i, v))) + }) + .collect(); + + let mut out = vec![0.0; texels.len()]; + for (i, v) in values { + if let Some(d) = out.get_mut(i) { + *d = v; + } + } + Some(out) +} + +/// Layer `id`'s enabled `mask` at the covered texels of `tile` whose offset in the tile passes +/// `wanted`, as (offset, value 0..=1); empty for a tile the mask has no plan for. +fn mask_tile( + inp: &Inputs, + id: LayerId, + mask: &Mask, + channels: &[Channel], + fields: &Fields, + (tx, ty): (u32, u32), + wanted: impl Fn(usize) -> bool, +) -> Vec<(usize, f32)> { + let Some(plan) = mask_plan(inp, id, mask, tx, ty, Some(fields)) else { return Vec::new() }; + + // Masks that read anchor points need the stack below the layer + let full = anchor_plan(inp, id, channels, tx, ty, Some(fields)); + tile_texels(inp.gbuf, tx, ty) + .filter(|&(_, _, o)| wanted(o)) + .map(|(x, y, o)| { + let mut texel = Texel::new(inp, x, y, o, 0.0); + if !full.is_empty() { + texel.anchors_below(&full, id); + } + (o, texel.mask(&plan)) + }) + .collect() +} + /// Tiles [`effect_histogram`] samples at most (a million texels). const HISTOGRAM_TILES: usize = 256; @@ -2175,6 +2231,45 @@ mod tests { assert!(vals.iter().any(|v| *v > 0.99) && vals.iter().any(|v| *v < 0.51), "{vals:?}"); } + #[test] + fn mask_at_reads_the_same_values_as_the_mask_image() { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [1.0, 1.0, 1.0], 1.0); + let eid = f.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + let pattern = Procedural::new(ProceduralKind::Checker); + mask.effects.push(Effect::new( + eid, + EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() }, + )); + f.project.layer_mut(id).unwrap().mask = Some(mask); + let maskless = f.project.alloc_id(); + let images = Default::default(); + let inp = Inputs { + project: &f.project, + ts: 0, + mesh: &f.mesh, + gbuf: &f.gbuf, + pixels: &f.pixels, + baked: &f.baked, + preview: None, + images: &images, + bounds: f.mesh.bounds(), + }; + + // Scattered texels, one twice, one outside the texture + let texels = [(0, 0), (13, 20), (63, 63), (40, 7), (13, 20), (64, 64)]; + let sparse = mask_at(&inp, id, &texels).unwrap(); + let image = mask_image(&inp, id, 64).unwrap(); + for (&(x, y), v) in texels.iter().zip(&sparse).take(5) { + let expected = f32::from(image[(y * 64 + x) as usize]) / 255.0; + assert!((v - expected).abs() <= 0.5 / 255.0 + 1e-6, "({x}, {y}): {v} vs {expected}"); + } + assert_eq!(sparse[5], 0.0, "uncovered texels read 0"); + assert!(sparse.iter().any(|v| *v > 0.99) && sparse.iter().take(5).any(|v| *v < 0.01), "{sparse:?}"); + assert!(mask_at(&inp, maskless, &texels).is_none(), "no mask, no values"); + } + #[test] fn blur_filter_softens_mask_edges() { let mut f = fixture(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5e34945c..ee940e06 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -17,6 +17,6 @@ pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, - mask_image, pad_tiles, + mask_at, mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ed07d645..ca7cdeea 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -25,6 +25,8 @@ pub mod layer_cmds; pub mod layer_ops; pub mod link_cmds; pub mod mask_cmds; +pub mod mask_preview; +mod mask_preview_pixel; pub mod material_lib; pub mod materials; pub mod materialx_cmds; diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs new file mode 100644 index 00000000..e7116d9d --- /dev/null +++ b/crates/engine/src/mask_preview.rs @@ -0,0 +1,163 @@ +//! Smart mask shelf previews: the real smart masks on a baked preview shape. The shape +//! ([`primitives::preview_orb`]) is baked once; each preset is then applied with +//! `mask.smart.apply`, read back from the compositor and seen from a fixed camera. + +use serde_json::json; +use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; +use texturecraft_geom::glam::{Quat, Vec2, Vec3}; +use texturecraft_geom::{primitives, surface_at}; + +pub use crate::mask_preview_pixel::MaskPreviewPixel; +use crate::{EngineError, Result, Session}; + +/// Texture and bake size of the preview shape in texels (at 256 the edge lines break up). +const TEXTURE_PX: u32 = 512; +/// Camera rays per thumbnail pixel along each axis (anti-aliased outline). +const SUPERSAMPLE: usize = 2; +/// AO and thickness rays per texel (the default is 64; fewer look the same at thumbnail size). +const OCCLUSION_RAYS: u32 = 12; +/// Mesh curvature rays per texel (the default is 32; fewer look the same at thumbnail size). +const CURVATURE_RAYS: u32 = 12; +/// Mesh curvature sampling radius relative to the bounding box: wide enough that edges read as +/// lines at thumbnail size, narrow enough that the round body does not count as an edge. +const CURVATURE_RADIUS: f32 = 0.005; +/// The mesh maps the smart mask generators read. +const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; +/// Camera: looking down by this angle, turned to show the front, left and top panels. +const CAMERA_PITCH_DEG: f32 = 35.0; +const CAMERA_YAW_DEG: f32 = -34.4; + +/// What one camera sub-pixel sees: the index of its texel in the preview's texel list and the +/// view-space normal there (None where the ray misses). +type CameraSample = Option<(usize, Vec3)>; + +/// The baked preview shape and what each thumbnail sub-pixel sees. +pub struct MaskPreview { + session: Session, + layer: LayerId, + size: usize, + /// The texels (x, y) the camera sees, each once. + texels: Vec<(u32, u32)>, + /// Per sub-pixel, row-major `(size · SUPERSAMPLE)²`. + samples: Vec, +} + +impl MaskPreview { + /// Bake the preview shape once and aim the camera for `size²` thumbnails. + pub fn new(size: usize) -> Result { + let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; + let set = session.doc.project.texture_set_mut(0)?; + set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; + set.bake.high_poly.use_low_as_high = true; + set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; + set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; + set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; + set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; + set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; + for map in BakedMap::ALL { + set.bake.maps.set_enabled(map, MAPS.contains(&map)); + } + let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; + session.bake_now(0, false)?; + + let (texels, samples) = camera_samples(&session, size * SUPERSAMPLE); + Ok(MaskPreview { session, layer, size, texels, samples }) + } + + /// Smart mask `id` per thumbnail pixel, row-major `size²`, None where the shape is not seen + /// (None for an unknown id). + pub fn render(&mut self, id: &str) -> Option>> { + crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; + // Nothing is undone here; the snapshots would pile up over the presets + self.session.undo.clear(); + let values = self.session.mask_at(self.layer, &self.texels)?; + + let fine = self.size * SUPERSAMPLE; + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..self.size * self.size) + .map(|i| { + let (x, y) = (i % self.size, i / self.size); + let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0); + for sy in 0..SUPERSAMPLE { + for sx in 0..SUPERSAMPLE { + let Some(&Some((texel, n))) = self.samples.get((y * SUPERSAMPLE + sy) * fine + x * SUPERSAMPLE + sx) else { continue }; + + mask += values.get(texel).copied().unwrap_or(0.0); + normal += n; + hits += 1.0; + } + } + (hits > 0.0).then(|| MaskPreviewPixel { mask: mask / hits, normal: normal.normalize_or_zero(), coverage: hits / sub_pixels }) + }) + .collect(); + Some(pixels) + } +} + +/// What each pixel of a `size²` orthographic view of the shape sees: the distinct texels hit, and +/// per pixel (row-major) its sample. +fn camera_samples(session: &Session, size: usize) -> (Vec<(u32, u32)>, Vec) { + let (lo, hi) = session.mesh.bounds(); + let center = (lo + hi) * 0.5; + let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); + let pitch = CAMERA_PITCH_DEG.to_radians(); + let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); + let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); + let right = turn * Vec3::X; + let up = right.cross(forward); + let max_texel = TEXTURE_PX - 1; + + let mut texels = Vec::new(); + let mut index_of = std::collections::HashMap::new(); + let samples = (0..size * size) + .map(|i| { + let ndc = Vec2::new(((i % size) as f32 + 0.5) / size as f32 * 2.0 - 1.0, 1.0 - ((i / size) as f32 + 0.5) / size as f32 * 2.0); + // Start well outside the shape so every ray enters it from the front + let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; + let hit = session.bvh.closest(origin, forward, radius * 8.0)?; + let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; + let texel = (((surface.uv.x * TEXTURE_PX as f32) as u32).min(max_texel), ((surface.uv.y * TEXTURE_PX as f32) as u32).min(max_texel)); + let index = *index_of.entry(texel).or_insert_with(|| { + texels.push(texel); + texels.len() - 1 + }); + let n = surface.nrm; + Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) + }) + .collect(); + (texels, samples) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Mean absolute difference of the masks of two previews over the pixels both see. + fn difference(a: &[Option], b: &[Option]) -> f32 { + let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); + pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 + } + + #[test] + fn smart_mask_previews_are_in_range_and_tell_edges_from_cavities() { + let size = 24; + let mut preview = MaskPreview::new(size).unwrap(); + for sm in crate::smart_masks::SMART_MASKS { + let px = preview.render(sm.id).unwrap_or_else(|| panic!("{}", sm.id)); + assert_eq!(px.len(), size * size, "{}", sm.id); + assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id); + let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect(); + assert!(seen.len() > size * size / 3, "{}: the shape fills the frame", sm.id); + for p in seen { + assert!((0.0..=1.0).contains(&p.mask) && (0.0..=1.0).contains(&p.coverage) && p.coverage > 0.0, "{}: {p:?}", sm.id); + assert!(p.normal.is_finite(), "{}: {p:?}", sm.id); + } + } + + let (edges, cavities) = (preview.render("edges_sharp").unwrap(), preview.render("dirt_cavities").unwrap()); + let shows = |px: &[Option]| px.iter().flatten().any(|p| p.mask > 0.5); + assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); + assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); + assert!(preview.render("nope").is_none()); + } +} diff --git a/crates/engine/src/mask_preview_pixel.rs b/crates/engine/src/mask_preview_pixel.rs new file mode 100644 index 00000000..bcde5629 --- /dev/null +++ b/crates/engine/src/mask_preview_pixel.rs @@ -0,0 +1,14 @@ +//! One pixel of a smart mask preview (see [`crate::mask_preview::MaskPreview`]). + +use texturecraft_geom::glam::Vec3; + +/// The smart mask value seen at a preview pixel, with what a display needs to shade the shape. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MaskPreviewPixel { + /// Mask value (0..=1). + pub mask: f32, + /// Surface normal in view space (+X right, +Y up, +Z towards the viewer). + pub normal: Vec3, + /// Fraction of the pixel the shape covers (0..=1, anti-aliased outline). + pub coverage: f32, +} diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 3c3aa130..1dc33631 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -1,6 +1,7 @@ -//! Shelf previews: built-in materials and smart masks evaluated on a unit sphere seen from +Z, -//! without a mesh or baked maps (generators that need mesh maps are approximated with world-space -//! noise). Cheap enough for lazily rendered thumbnails. +//! Shelf previews: built-in materials evaluated on a unit sphere seen from +Z, without a mesh or +//! baked maps (generators that need mesh maps are approximated with world-space noise), and +//! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked +//! preview ([`crate::mask_preview`]). use texturecraft_compose::pattern::{Coords, procedural, world_noise}; use texturecraft_core::{ @@ -183,13 +184,6 @@ pub fn filter(id: &str, size: usize) -> Option>> { ) } -/// Preview of smart mask `id`: the mask value per pixel (None for an unknown id). -pub fn smart_mask(id: &str, size: usize) -> Option>> { - let (bg, fx) = crate::smart_masks::preset(id)?; - let m = crate::smart_masks::build_mask(&mut Project::new("preview", ""), bg, fx); - Some(sphere_normals(size).map(|n| n.map(|n| mask(&m, &coords(n)))).collect()) -} - #[cfg(test)] mod tests { use super::*; @@ -202,11 +196,7 @@ mod tests { assert!(center.base.iter().chain([¢er.metallic, ¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", m.id); assert!(px[0].is_none(), "corners are outside the sphere"); } - for sm in crate::smart_masks::SMART_MASKS { - let px = smart_mask(sm.id, 16).unwrap_or_else(|| panic!("{}", sm.id)); - assert!(px.iter().flatten().all(|v| (0.0..=1.0).contains(v)), "{}", sm.id); - } - assert!(material("nope", 8).is_none() && smart_mask("nope", 8).is_none() && filter("nope", 8).is_none()); + assert!(material("nope", 8).is_none() && filter("nope", 8).is_none()); for f in crate::filter_lib::FILTERS { let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id)); let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id)); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 7ec12739..214bd69f 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -829,6 +829,13 @@ impl Session { Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect()) } + /// Layer `id`'s mask (0..=1) at `texels` (x, y) of its texture set, in order (None without a + /// mask); evaluates only those texels. + pub fn mask_at(&self, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let (ts, _, _) = self.doc.project.locate(id)?; + self.with_inputs(ts, |inp| texturecraft_compose::mask_at(inp, id, texels)) + } + /// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's /// mask, or for a content effect the layer's `channel` (None for an unknown effect). pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option> { diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs index 6403faed..29bad947 100644 --- a/crates/geom/src/primitives.rs +++ b/crates/geom/src/primitives.rs @@ -63,9 +63,17 @@ impl Builder { } } + /// The mesh of one material, with tangents. fn finish(self, material: &str) -> Mesh { + let mut m = self.into_mesh(material); + m.compute_tangents(); + m + } + + /// The mesh of one material, without tangents. + fn into_mesh(self, material: &str) -> Mesh { let count = self.idx.len() as u32; - let mut m = Mesh { + Mesh { positions: self.p, normals: self.n, uvs: self.uv, @@ -75,9 +83,7 @@ impl Builder { submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], materials: vec![material.into()], diagonals: self.diag, - }; - m.compute_tangents(); - m + } } } @@ -189,6 +195,132 @@ fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize }); } +/// [`preview_orb`]: half-size of the cube that cuts the unit sphere flat (each face rim is the +/// circle where they meet). +const ORB_CUT: f32 = 0.8; +/// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius. +const ORB_PANEL_VALLEY: f32 = 0.88; + +/// The smart mask preview shape: a sphere cut flat by a cube on six sides, on a thin round base. +/// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly +/// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys +/// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it +/// meets the body) and plain rounded corners (gradients). Faces +Z (front), -X (left) and +Y (top) +/// carry the panels, so the shape is made to be seen from the front left, slightly from above. +/// The body takes the top 79 % of the UV square, the base the bottom 19 %. +pub fn preview_orb() -> Mesh { + // Grid rows (columns: twice as many); fewer blur the panel walls, more cost bake time + const ROWS: usize = 300; + const BODY_UV_HEIGHT: f32 = 0.79; + const BASE_UV: UvRect = UvRect { o: Vec2::new(0.0, 0.81), s: Vec2::new(1.0, 0.19) }; + const BASE_RADIUS: f32 = 0.95; + const BASE_HALF_HEIGHT: f32 = 0.025; + const BASE_Y: f32 = -0.6; + const BASE_RIM_STEPS: usize = 12; + const BASE_SEGMENTS: usize = 256; + + let mut b = Builder::default(); + b.grid(ROWS, ROWS * 2, |i, j| { + let (u, v) = (j as f32 / (ROWS * 2) as f32, i as f32 / ROWS as f32); + let (theta, phi) = (v * PI, u * TAU + PI * 1.5); + let dir = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()); + (dir * preview_orb_radius(dir), dir, Vec2::new(u, v * BODY_UV_HEIGHT)) + }); + + // Base: a thin disc with a rounded rim (a half circle from its top face to its bottom face) + let mut profile = vec![(0.0, BASE_HALF_HEIGHT)]; + for k in 0..=BASE_RIM_STEPS { + let a = k as f32 / BASE_RIM_STEPS as f32 * PI; + profile.push((BASE_RADIUS - BASE_HALF_HEIGHT + BASE_HALF_HEIGHT * a.sin(), BASE_HALF_HEIGHT * a.cos())); + } + profile.push((0.0, -BASE_HALF_HEIGHT)); + lathe_into(&mut b, Vec3::Y * BASE_Y, &profile, BASE_SEGMENTS, BASE_UV); + + let mut m = b.into_mesh("Preview"); + // Normals from the triangles: the panel walls are too steep for the sphere's directions + m.compute_normals(); + // Body and base both run U around the vertical axis, so the tangent is that direction (a + // fraction of the cost of the general tangent pass on this many triangles) + m.tangents = m + .positions + .iter() + .zip(&m.normals) + .map(|(p, n)| { + let around = Vec3::new(p.z, 0.0, -p.x).try_normalize().unwrap_or(Vec3::X); + (around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(1.0) + }) + .collect(); + m +} + +/// Distance from the centre of the [`preview_orb`] body along unit direction `d`. +fn preview_orb_radius(d: Vec3) -> f32 { + // Rim blends: the sharp faces, and the softly blended left face + const SHARP_BLEND: f32 = 0.035; + const SOFT_BLEND: f32 = 0.18; + // Domed panels: valley depth below the face, dome rise past it; the left panel is smaller + const PANEL_DEPTH: f32 = 0.11; + const PANEL_BULGE: f32 = 0.04; + const LEFT_PANEL_SCALE: f32 = 0.9; + // Slot around the middle: centre height, half-width, edge rounding, depth; it fades out over + // this fraction of the left panel's rim + const SLOT_Y: f32 = -0.03; + const SLOT_HALF_WIDTH: f32 = 0.05; + const SLOT_ROUNDING: f32 = 0.015; + const SLOT_DEPTH: f32 = 0.12; + const SLOT_FADE: f32 = 0.04; + + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let smooth = |a: f32, b: f32, x: f32| { + let t = ((x - a) / (b - a)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) + }; + // Polynomial smooth minimum with blend radius k + let smin = |a: f32, b: f32, k: f32| { + let h = (0.5 + 0.5 * (b - a) / k).clamp(0.0, 1.0); + b + (a - b) * h - k * h * (1.0 - h) + }; + // Domed panel at `rho` (radius in face units) inside a face of rim `rim`: a steep wall from + // the rim into a valley, then a dome rising slightly past the face over the middle + let panel = |rho: f32, rim: f32| { + let valley = rim * ORB_PANEL_VALLEY; + if rho < valley { + PANEL_BULGE - (PANEL_BULGE + PANEL_DEPTH) * (rho / valley).powi(3) + } else { + -PANEL_DEPTH * (1.0 - ((rho - valley) / (rim - valley)).min(1.0)) + } + }; + let face_rho = |along: f32, u: f32, v: f32| (u * u + v * v).sqrt() / along.max(1e-3); + + // The cut: sharp rims except the softly blended left face + let mut radius = 1.0f32; + for (along, blend) in [(d.x, SHARP_BLEND), (-d.x, SOFT_BLEND), (d.y, SHARP_BLEND), (-d.y, SHARP_BLEND), (d.z, SHARP_BLEND), (-d.z, SHARP_BLEND)] { + // Directions facing away from a face stay on the sphere (9 = far past it) + let to_face = if along > 1e-3 { ORB_CUT / along } else { 9.0 }; + radius = smin(radius, to_face, blend); + } + + let a = d.abs(); + let left_rim = rim * LEFT_PANEL_SCALE; + let mut relief = 0.0; + if d.z > 0.0 && a.z >= a.x && a.z >= a.y { + relief += panel(face_rho(d.z, d.x, d.y), rim); + } + if d.x < 0.0 && a.x >= a.y && a.x >= a.z { + relief += panel(face_rho(-d.x, d.y, d.z), left_rim); + } + if d.y > 0.0 && a.y >= a.x && a.y >= a.z { + relief += panel(face_rho(d.y, d.x, d.z), rim); + } + + // Slot around the middle, stopping at the left panel + let in_left_panel = if d.x < 0.0 { 1.0 - smooth(left_rim * (1.0 - SLOT_FADE), left_rim * (1.0 + SLOT_FADE), face_rho(-d.x, d.y, d.z)) } else { 0.0 }; + let slot_band = 1.0 - smooth(SLOT_HALF_WIDTH - SLOT_ROUNDING, SLOT_HALF_WIDTH + SLOT_ROUNDING, (d.y - SLOT_Y).abs()); + relief -= SLOT_DEPTH * slot_band * (1.0 - in_left_panel); + + radius + relief +} + /// A flat disk facing up (+Y) or down, with planar UVs inside `r`. fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) { let n = if up { Vec3::Y } else { Vec3::NEG_Y }; @@ -340,6 +472,8 @@ pub fn builtin(id: &str) -> Option { "plane" => plane(2.0, 16), "crate" => crate_scene(), "udim_plane" | "udimplane" => udim_plane(), + // Not offered for new projects (not in BUILTINS): the smart mask preview session's mesh + "preview_orb" => preview_orb(), _ => return None, }) } @@ -396,6 +530,22 @@ mod tests { assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::>(), vec![(0, 0), (1, 0)]); } + #[test] + fn preview_orb_is_well_formed_with_domed_panels() { + let m = preview_orb(); + check(&m, 1.0); + + // Above the middle slot, the front panel's dome rises past the cut face and its valley + // sits below it + let front_depth = |rho: f32| { + let d = Vec3::new(0.0, rho, 1.0).normalize(); + preview_orb_radius(d) * d.z + }; + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let (dome, valley) = (front_depth(0.2), front_depth(rim * ORB_PANEL_VALLEY)); + assert!(dome > ORB_CUT && valley < ORB_CUT - 0.05, "dome {dome}, valley {valley}"); + } + #[test] fn material_ball_has_two_materials() { let m = material_ball(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c6112eb3..df2d1c7a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,6 +16,7 @@ pub mod fonts; pub mod gpu; pub mod i18n; pub mod keymap; +mod mask_previews; pub mod menus; pub mod parity; pub mod profile; diff --git a/crates/ui-egui/src/mask_previews.rs b/crates/ui-egui/src/mask_previews.rs new file mode 100644 index 00000000..fc6018e4 --- /dev/null +++ b/crates/ui-egui/src/mask_previews.rs @@ -0,0 +1,104 @@ +//! Smart mask shelf thumbnails: every smart mask on the baked preview shape, rendered together on +//! a worker the first time the shelf asks for one (baking the shape takes about two seconds on +//! the CPU; on the web the work runs inline). + +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::time::Duration; + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::mask_preview::{MaskPreview, MaskPreviewPixel}; +use texturecraft_engine::smart_masks::SMART_MASKS; +use texturecraft_engine::texel::linear_to_srgb; + +/// View-space directions of the key light (upper left) and a weaker fill (right), and how much +/// each lights the surface. +const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; +const FILL: [f32; 3] = [0.7, -0.1, 0.7]; +const AMBIENT: f32 = 0.1; +const KEY_STRENGTH: f32 = 0.8; +const FILL_STRENGTH: f32 = 0.35; +/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the +/// shape reads without looking glossy. +const UNMASKED_ALBEDO: f32 = 0.006; +const SHEEN: f32 = 0.1; +const SHEEN_EXPONENT: f32 = 40.0; +/// Where the mask is full: white, darkened at most this much where unlit. +const WHITE_SHADING: f32 = 0.2; +/// How often the shelf checks for the thumbnails while they render. +const POLL: Duration = Duration::from_millis(100); + +/// Smart mask thumbnails by id, as the worker sends them. +type Thumbnails = Vec<(&'static str, ColorImage)>; + +/// Where the smart mask thumbnails are. +#[derive(Default)] +pub enum MaskPreviews { + #[default] + NotStarted, + Rendering(Receiver), + /// Handed out (or the worker failed; the tiles keep their placeholder). + Finished, +} + +impl MaskPreviews { + /// Start rendering `size²` thumbnails on the first call; the finished thumbnails on the call + /// that finds them done (None before and after). + pub fn poll(&mut self, ctx: &egui::Context, size: usize) -> Option { + if matches!(self, MaskPreviews::NotStarted) { + *self = MaskPreviews::Rendering(crate::spawn_worker("texturecraft-mask-previews", move || render(size))); + } + let MaskPreviews::Rendering(rx) = self else { return None }; + + match rx.try_recv() { + Ok(thumbnails) => { + *self = MaskPreviews::Finished; + Some(thumbnails) + } + Err(TryRecvError::Empty) => { + ctx.request_repaint_after(POLL); + None + } + // The worker stopped without a result + Err(TryRecvError::Disconnected) => { + *self = MaskPreviews::Finished; + None + } + } + } +} + +/// Every smart mask's `size²` thumbnail (empty when the preview shape fails to bake). +fn render(size: usize) -> Thumbnails { + let mut preview = match MaskPreview::new(size) { + Ok(p) => p, + Err(e) => { + log::warn!("smart mask previews: {e}"); + return Vec::new(); + } + }; + SMART_MASKS.iter().filter_map(|m| Some((m.id, image(size, &preview.render(m.id)?)))).collect() +} + +/// A thumbnail (sRGB, transparent outside the shape) from preview pixels (row-major `size²`): +/// the mask as white over a near-black surface lit softly from the upper left. No environment +/// reflections. +fn image(size: usize, pixels: &[Option]) -> ColorImage { + let key = Vec3::from(KEY).normalize(); + let fill = Vec3::from(FILL).normalize(); + let half = (key + Vec3::Z).normalize(); + let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (out, p) in img.pixels.iter_mut().zip(pixels) { + let Some(p) = p else { continue }; + + let n = p.normal; + let shading = AMBIENT + KEY_STRENGTH * n.dot(key).max(0.0) + FILL_STRENGTH * n.dot(fill).max(0.0); + let unmasked = UNMASKED_ALBEDO * shading + SHEEN * n.dot(half).max(0.0).powf(SHEEN_EXPONENT); + let masked = 1.0 - WHITE_SHADING * (1.0 - shading.min(1.0)); + let linear = unmasked + (masked - unmasked) * p.mask.clamp(0.0, 1.0); + let gray = (linear_to_srgb(linear.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(gray, gray, gray, (p.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + } + img +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index a2d85712..f5590b31 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,6 +1,7 @@ -//! Thumbnails: shaded material spheres, smart mask spheres, procedural swatches and brush alpha -//! previews, rendered on the CPU into cached egui textures (no image assets). New shelf -//! thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a frame. +//! Thumbnails: shaded material spheres, smart masks on a baked preview shape, procedural swatches +//! and brush alpha previews, rendered on the CPU into cached egui textures (no image assets). New +//! shelf thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a +//! frame; the smart mask previews render together on a worker. use std::collections::HashMap; @@ -11,6 +12,8 @@ use texturecraft_engine::paint::{BrushAlpha, BrushSettings, Shape, alphas}; use texturecraft_engine::preview::{self, Sample}; use texturecraft_engine::texel::linear_to_srgb; +use crate::mask_previews::MaskPreviews; + /// Shelf thumbnails rendered per frame at most (the rest follow on the next frames). const PER_FRAME: usize = 2; /// Shelf sphere thumbnail size in pixels. @@ -24,6 +27,7 @@ pub struct Thumbs { images: HashMap, /// (frame, thumbnails rendered in it). budget: (u64, usize), + mask_previews: MaskPreviews, } fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { @@ -161,14 +165,20 @@ impl Thumbs { self.shelf(ctx, format!("mat:{id}"), || sphere_image(SPHERE_PX, &preview::material(id, SPHERE_PX).unwrap_or_default())) } - /// Sphere thumbnail of smart mask `id`: white where the mask applies, over dark gray. + /// Thumbnail of smart mask `id` on the baked preview shape (None while the thumbnails + /// render; they all arrive together). pub fn smart_mask(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("mask:{id}"), || { - let px = preview::smart_mask(id, SPHERE_PX).unwrap_or_default(); - let samples: Vec> = - px.iter().map(|m| m.map(|m| Sample { base: [0.04 + 0.76 * m; 3], metallic: 0.0, roughness: 0.6, height: 0.0 })).collect(); - sphere_image(SPHERE_PX, &samples) - }) + let key = format!("mask:{id}"); + if let Some(t) = self.shelf.get(&key) { + return Some(t.clone()); + } + + for (mask_id, image) in self.mask_previews.poll(ctx, SPHERE_PX).unwrap_or_default() { + let mask_key = format!("mask:{mask_id}"); + let t = ctx.load_texture(format!("thumb_{mask_key}"), image, TextureOptions::LINEAR); + self.shelf.insert(mask_key, t); + } + self.shelf.get(&key).cloned() } /// Sphere thumbnail of library filter `id` applied to a sample material. From 476d5ecc8be8648dde71c613964a3a04fb132758 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Thu, 5 Nov 2026 18:54:07 -0500 Subject: [PATCH 14/73] Guard preview inputs and optimize sparse mask reads --- crates/compose/src/eval.rs | 270 +++++++++++++++++---------- crates/engine/src/mask_preview.rs | 41 ++-- crates/engine/src/session.rs | 8 +- crates/ui-egui/tests/ui_snapshots.rs | 29 +++ 4 files changed, 235 insertions(+), 113 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 56b32cd8..ec75cd97 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1835,103 +1835,115 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) written } -/// The mask of layer `id` as an 8-bit grayscale image of `size × size` stretched over the -/// texture set (nearest texel; uncovered texels black). None when the layer has no enabled mask. -pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { - let mask = layer_mask(inp.project, id).filter(|m| m.enabled)?; - let channels = inp.project.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); - let (w, h) = (inp.gbuf.width, inp.gbuf.height); - let all = all_tiles(w, h); - let fields = neighbourhood_fields(inp, &channels, &all); - let tiles: HashMap<(u32, u32), Vec> = all +/// The layer mask as a square grayscale image, using nearest texels and black outside the mesh +/// Returns None without an enabled mask +pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { + let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; + let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + let coordinates = all_tiles(width, height); + let fields = neighbourhood_fields(inputs, &channels, &coordinates); + let tiles: HashMap<(u32, u32), Vec> = coordinates .par_iter() .map(|&tile| { - let mut buf = vec![0u8; TILE_AREA]; - for (o, v) in mask_tile(inp, id, mask, &channels, &fields, tile, |_| true) { - if let Some(b) = buf.get_mut(o) { - *b = (v * 255.0 + 0.5) as u8; + let mut values = vec![0u8; TILE_AREA]; + for (offset, value) in mask_tile(inputs, id, mask, &channels, &fields, tile, 0..TILE_AREA) { + if let Some(destination) = values.get_mut(offset) { + *destination = (value * 255.0 + 0.5) as u8; } } - (tile, buf) + (tile, values) }) .collect(); let size = size.max(1); - let mut out = vec![0u8; (size * size) as usize]; + let mut output = vec![0u8; (size * size) as usize]; for y in 0..size { for x in 0..size { - let (sx, sy) = ((x as u64 * w as u64 / size as u64) as u32, (y as u64 * h as u64 / size as u64) as u32); - if let Some(t) = tiles.get(&(sx / TILE, sy / TILE)) - && let Some(v) = t.get(((sy % TILE) * TILE + sx % TILE) as usize) - && let Some(d) = out.get_mut((y * size + x) as usize) + let sample_x = (u64::from(x) * u64::from(width) / u64::from(size)) as u32; + let sample_y = (u64::from(y) * u64::from(height) / u64::from(size)) as u32; + if let Some(tile) = tiles.get(&(sample_x / TILE, sample_y / TILE)) + && let Some(value) = tile.get(((sample_y % TILE) * TILE + sample_x % TILE) as usize) + && let Some(destination) = output.get_mut((y * size + x) as usize) { - *d = *v; + *destination = *value; } } } - Some(out) + Some(output) } -/// The mask of layer `id` (0..=1) at `texels` (x, y) of the texture set, in order; 0 where the -/// mesh does not cover a texel. Only the requested texels are evaluated, so a sparse read (a -/// preview's visible texels) costs a fraction of [`mask_image`]. None when the layer has no -/// enabled mask. -pub fn mask_at(inp: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { - let mask = layer_mask(inp.project, id).filter(|m| m.enabled)?; - let channels = inp.project.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); - // Neighbourhood effects (blur, warp) read past the requested texels, so their fields cover - // every tile, as in `mask_image` - let fields = neighbourhood_fields(inp, &channels, &all_tiles(inp.gbuf.width, inp.gbuf.height)); +/// Mask values at texture-set coordinates, in request order; None without an enabled mask +/// Uncovered and out-of-range texels read zero; neighbourhood filters also evaluate surrounding texels +pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; + let mut output = vec![0.0; texels.len()]; + + // Group valid requests before planning effects, which may resample painted tiles + let mut requested: HashMap<(u32, u32), Vec<(usize, usize)>> = HashMap::new(); + for (index, &(x, y)) in texels.iter().enumerate() { + if x >= inputs.gbuf.width || y >= inputs.gbuf.height { + continue; + } - // Per tile: offset in the tile -> indices in `texels` asking for it - let mut wanted: HashMap<(u32, u32), HashMap>> = HashMap::new(); - for (i, &(x, y)) in texels.iter().enumerate() { let offset = ((y % TILE) * TILE + x % TILE) as usize; - wanted.entry((x / TILE, y / TILE)).or_default().entry(offset).or_default().push(i); + requested.entry((x / TILE, y / TILE)).or_default().push((offset, index)); } - let values: Vec<(usize, f32)> = wanted - .par_iter() - .flat_map_iter(|(&tile, offsets)| { - mask_tile(inp, id, mask, &channels, &fields, tile, |o| offsets.contains_key(&o)) - .into_iter() - .flat_map(move |(o, v)| offsets.get(&o).into_iter().flatten().map(move |&i| (i, v))) + + if requested.is_empty() { + return Some(output); + } + + let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); + // Filters and anchors can depend on texels outside the requested tiles + let fields = neighbourhood_fields(inputs, &channels, &all_tiles(inputs.gbuf.width, inputs.gbuf.height)); + let values: Vec<(usize, f32)> = requested + .par_iter_mut() + .flat_map_iter(|(&tile, requests)| { + requests.sort_unstable_by_key(|&(offset, _)| offset); + let groups = requests.chunk_by(|left, right| left.0 == right.0); + let offsets = groups.clone().filter_map(|group| group.first().map(|&(offset, _)| offset)); + mask_tile(inputs, id, mask, &channels, &fields, tile, offsets) + .zip(groups) + .flat_map(|((_, value), group)| group.iter().map(move |&(_, index)| (index, value))) }) .collect(); - let mut out = vec![0.0; texels.len()]; - for (i, v) in values { - if let Some(d) = out.get_mut(i) { - *d = v; + for (index, value) in values { + if let Some(destination) = output.get_mut(index) { + *destination = value; } } - Some(out) + Some(output) } -/// Layer `id`'s enabled `mask` at the covered texels of `tile` whose offset in the tile passes -/// `wanted`, as (offset, value 0..=1); empty for a tile the mask has no plan for. -fn mask_tile( - inp: &Inputs, +/// Mask values in offset order, including zeros for uncovered texels so request groups stay aligned +fn mask_tile<'a>( + inputs: &'a Inputs<'a>, id: LayerId, - mask: &Mask, + mask: &'a Mask, channels: &[Channel], - fields: &Fields, - (tx, ty): (u32, u32), - wanted: impl Fn(usize) -> bool, -) -> Vec<(usize, f32)> { - let Some(plan) = mask_plan(inp, id, mask, tx, ty, Some(fields)) else { return Vec::new() }; + fields: &'a Fields, + (tile_x, tile_y): (u32, u32), + offsets: impl Iterator + 'a, +) -> impl Iterator + 'a { + let plan = mask_plan(inputs, id, mask, tile_x, tile_y, Some(fields)); + let anchor_stack = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(fields)); + offsets.map(move |offset| { + let Some(plan) = plan.as_ref() else { return (offset, 0.0) }; - // Masks that read anchor points need the stack below the layer - let full = anchor_plan(inp, id, channels, tx, ty, Some(fields)); - tile_texels(inp.gbuf, tx, ty) - .filter(|&(_, _, o)| wanted(o)) - .map(|(x, y, o)| { - let mut texel = Texel::new(inp, x, y, o, 0.0); - if !full.is_empty() { - texel.anchors_below(&full, id); - } - (o, texel.mask(&plan)) - }) - .collect() + let x = tile_x * TILE + (offset % TILE as usize) as u32; + let y = tile_y * TILE + (offset / TILE as usize) as u32; + if x >= inputs.gbuf.width || y >= inputs.gbuf.height || inputs.gbuf.tri.get((y * inputs.gbuf.width + x) as usize).is_none_or(|tri| *tri == NO_TRI) { + return (offset, 0.0); + } + + let mut texel = Texel::new(inputs, x, y, offset, 0.0); + if !anchor_stack.is_empty() { + texel.anchors_below(&anchor_stack, id); + } + (offset, texel.mask(plan)) + }) } /// Tiles [`effect_histogram`] samples at most (a million texels). @@ -2231,43 +2243,109 @@ mod tests { assert!(vals.iter().any(|v| *v > 0.99) && vals.iter().any(|v| *v < 0.51), "{vals:?}"); } + fn assert_sparse_mask_matches_image(fixture: &Fixture, layer: LayerId, texels: &[(u32, u32)]) -> Option> { + let images = ImageStore::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + let sparse = mask_at(&inputs, layer, texels); + let image = mask_image(&inputs, layer, fixture.gbuf.width); + assert_eq!(sparse.is_some(), image.is_some()); + let values = sparse?; + let image = image?; + assert_eq!(values.len(), texels.len()); + + for (&(x, y), &value) in texels.iter().zip(&values) { + let expected = + if x < fixture.gbuf.width && y < fixture.gbuf.height { f32::from(image[(y * fixture.gbuf.width + x) as usize]) / 255.0 } else { 0.0 }; + assert!((value - expected).abs() <= 0.5 / 255.0 + 1e-6, "({x}, {y}): {value} vs {expected}"); + } + Some(values) + } + #[test] fn mask_at_reads_the_same_values_as_the_mask_image() { - let mut f = fixture(); - let id = fill_layer(&mut f.project, [1.0, 1.0, 1.0], 1.0); - let eid = f.project.alloc_id(); + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 128); + fixture.project.texture_sets[0].resolution = 128; + fixture.gbuf.tri[30 * 128 + 90] = NO_TRI; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let maskless = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let effect = fixture.project.alloc_id(); let mut mask = Mask::new(MaskBackground::Black); let pattern = Procedural::new(ProceduralKind::Checker); mask.effects.push(Effect::new( - eid, + effect, EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() }, )); - f.project.layer_mut(id).unwrap().mask = Some(mask); - let maskless = f.project.alloc_id(); - let images = Default::default(); - let inp = Inputs { - project: &f.project, - ts: 0, - mesh: &f.mesh, - gbuf: &f.gbuf, - pixels: &f.pixels, - baked: &f.baked, - preview: None, - images: &images, - bounds: f.mesh.bounds(), - }; + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); - // Scattered texels, one twice, one outside the texture - let texels = [(0, 0), (13, 20), (63, 63), (40, 7), (13, 20), (64, 64)]; - let sparse = mask_at(&inp, id, &texels).unwrap(); - let image = mask_image(&inp, id, 64).unwrap(); - for (&(x, y), v) in texels.iter().zip(&sparse).take(5) { - let expected = f32::from(image[(y * 64 + x) as usize]) / 255.0; - assert!((v - expected).abs() <= 0.5 / 255.0 + 1e-6, "({x}, {y}): {v} vs {expected}"); + // Cross tile boundaries and include duplicates, a UV hole and invalid coordinates + let texels = [(0, 0), (0, 40), (63, 63), (64, 64), (127, 127), (0, 40), (90, 30), (128, 0), (0, 128), (u32::MAX, u32::MAX)]; + let values = assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap(); + assert!(values.iter().any(|value| *value > 0.99) && values.iter().take(6).any(|value| *value < 0.01)); + assert_eq!(&values[6..], &[0.0; 4]); + assert_eq!(assert_sparse_mask_matches_image(&fixture, layer, &[]), Some(Vec::new())); + assert!(assert_sparse_mask_matches_image(&fixture, maskless, &texels).is_none()); + let missing = fixture.project.alloc_id(); + assert!(assert_sparse_mask_matches_image(&fixture, missing, &texels).is_none()); + fixture.project.layer_mut(layer).unwrap().mask.as_mut().unwrap().enabled = false; + assert!(assert_sparse_mask_matches_image(&fixture, layer, &texels).is_none()); + } + + #[test] + fn mask_at_ignores_out_of_range_texels_before_resampling_paint() { + let mut fixture = fixture(); + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let paint = fixture.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(paint, EffectKind::Paint)); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + fixture.pixels.mask_mut(paint, (32, 32)).set(4, 5, &[u16::MAX; 2]); + + let texels = [(8, 10), (u32::MAX, 0), (0, u32::MAX), (u32::MAX, u32::MAX), (64, 0), (0, 64)]; + let values = assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap(); + assert!(values[0] > 0.5, "valid texels still read resampled paint"); + assert_eq!(&values[1..], &[0.0; 5]); + assert_eq!(assert_sparse_mask_matches_image(&fixture, layer, &texels[1..]), Some(vec![0.0; 5])); + } + + #[test] + fn mask_at_preserves_anchors_and_neighbourhood_filters_across_tiles() { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 128); + fixture.project.texture_sets[0].resolution = 128; + let lower = fill_layer(&mut fixture.project, [0.0; 3], 1.0); + let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(lower).unwrap().kind else { panic!("expected a fill layer") }; + + fill.sources.insert(Channel::BaseColor, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }); + let anchor = content_fx(&mut fixture, lower, EffectKind::Anchor); + let upper = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new( + fixture.project.alloc_id(), + EffectKind::Fill { source: Source::Anchor { anchor, channel: Channel::BaseColor }, projection: Projection::default() }, + )); + fixture.project.layer_mut(upper).unwrap().mask = Some(mask.clone()); + let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); + let original = assert_sparse_mask_matches_image(&fixture, upper, &texels).unwrap(); + assert!(original.iter().any(|value| *value > 0.99) && original.iter().any(|value| *value < 0.01), "the anchor supplies the checker"); + + for filter in [Filter::Blur { radius: 64.0 }, Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }] { + let mut filtered = mask.clone(); + filtered.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(filter))); + fixture.project.layer_mut(upper).unwrap().mask = Some(filtered); + let values = assert_sparse_mask_matches_image(&fixture, upper, &texels).unwrap(); + assert!(values.iter().zip(&original).any(|(value, original)| (value - original).abs() > 0.1), "the filter changes the anchor values"); } - assert_eq!(sparse[5], 0.0, "uncovered texels read 0"); - assert!(sparse.iter().any(|v| *v > 0.99) && sparse.iter().take(5).any(|v| *v < 0.01), "{sparse:?}"); - assert!(mask_at(&inp, maskless, &texels).is_none(), "no mask, no values"); } #[test] diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs index e7116d9d..9f7673c4 100644 --- a/crates/engine/src/mask_preview.rs +++ b/crates/engine/src/mask_preview.rs @@ -14,6 +14,8 @@ use crate::{EngineError, Result, Session}; const TEXTURE_PX: u32 = 512; /// Camera rays per thumbnail pixel along each axis (anti-aliased outline). const SUPERSAMPLE: usize = 2; +/// Bound camera samples and output allocations for this thumbnail-only renderer +const MAX_PREVIEW_SIZE_PX: usize = 512; /// AO and thickness rays per texel (the default is 64; fewer look the same at thumbnail size). const OCCLUSION_RAYS: u32 = 12; /// Mesh curvature rays per texel (the default is 32; fewer look the same at thumbnail size). @@ -43,21 +45,27 @@ pub struct MaskPreview { } impl MaskPreview { - /// Bake the preview shape once and aim the camera for `size²` thumbnails. + /// Bake the preview shape for square thumbnails with sides of 1..=512 pixels pub fn new(size: usize) -> Result { - let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; - let set = session.doc.project.texture_set_mut(0)?; - set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; - set.bake.high_poly.use_low_as_high = true; - set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; - set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; - set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; - set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; - set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; - for map in BakedMap::ALL { - set.bake.maps.set_enabled(map, MAPS.contains(&map)); + if !(1..=MAX_PREVIEW_SIZE_PX).contains(&size) { + return Err(EngineError::Other(format!("mask preview size must be between 1 and {MAX_PREVIEW_SIZE_PX} pixels"))); } - let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; + + let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; + let settings = &mut session.doc.project.texture_set_mut(0)?.bake; + settings.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; + settings.high_poly.use_low_as_high = true; + settings.maps.curvature.parameters.method = CurvatureMethod::Mesh; + settings.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; + settings.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; + settings.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; + settings.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; + + for map in BakedMap::ALL { + settings.maps.set_enabled(map, MAPS.contains(&map)); + } + + let layer = *session.doc.project.texture_set(0)?.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; session.bake_now(0, false)?; let (texels, samples) = camera_samples(&session, size * SUPERSAMPLE); @@ -138,6 +146,13 @@ mod tests { pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 } + #[test] + fn invalid_preview_sizes_return_errors() { + for size in [usize::MAX / 2 + 1, 0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX] { + assert!(MaskPreview::new(size).is_err(), "size {size} should be rejected before baking"); + } + } + #[test] fn smart_mask_previews_are_in_range_and_tell_edges_from_cavities() { let size = 24; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 214bd69f..aeaa5550 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -829,11 +829,11 @@ impl Session { Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect()) } - /// Layer `id`'s mask (0..=1) at `texels` (x, y) of its texture set, in order (None without a - /// mask); evaluates only those texels. + /// Mask values at texture-set coordinates in request order; None without an enabled mask + /// Uncovered and out-of-range texels read zero; neighbourhood filters also read surrounding texels pub fn mask_at(&self, id: LayerId, texels: &[(u32, u32)]) -> Option> { - let (ts, _, _) = self.doc.project.locate(id)?; - self.with_inputs(ts, |inp| texturecraft_compose::mask_at(inp, id, texels)) + let (texture_set, _, _) = self.doc.project.locate(id)?; + self.with_inputs(texture_set, |inputs| texturecraft_compose::mask_at(inputs, id, texels)) } /// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 0f42158f..07a9b9fb 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -158,3 +158,32 @@ fn window_snapshots() { harness.event(egui::Event::PointerButton { pos: cursor_position, button, pressed: false, modifiers }); harness.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); } + +#[test] +#[ignore] +fn smart_mask_shelf_snapshot() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { + eprintln!("set TC_UI_SNAPSHOTS= to write the picture"); + return; + }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let session = + texturecraft_engine::Session::new_project("Mask previews", texturecraft_engine::geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = 2; + let context = harness.ctx.clone(); + let started = std::time::Instant::now(); + loop { + harness.run_steps(1); + let thumbnails = &mut harness.state_mut().thumbs; + if texturecraft_engine::smart_masks::SMART_MASKS.iter().all(|preset| thumbnails.smart_mask(&context, preset.id).is_some()) { + break; + } + assert!(started.elapsed() < std::time::Duration::from_secs(60), "smart mask thumbnails did not arrive"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + eprintln!("all smart mask thumbnails ready after {:.3} s", started.elapsed().as_secs_f64()); + save(&mut harness, &output_dir, "smart-mask-shelf"); +} From d9bc1ef6d8885dd3920c8aea37680122592cf1e7 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 00:04:49 +0000 Subject: [PATCH 15/73] UI: fit the unsaved-changes dialog to its contents The button row was a right-to-left layout placed straight in the dialog body, which centres its contents in all the remaining height, so the auto-sized window grew to 420 px. Wrapping it in a horizontal row (as the New project dialog does) brings it to 119 px. Adds a regression test on the dialog's window height. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/windows.rs | 49 ++++++++++++++++----------- crates/ui-egui/tests/close_unsaved.rs | 14 ++++++++ 2 files changed, 44 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 3672ad45..0c35d957 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -40,48 +40,59 @@ pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved /// (in the browser, Save downloads the project). fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { use crate::state::Unsaved; + if ctx.input(|i| i.viewport().close_requested()) && ask_to_save(app, Unsaved::Quit) { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); } - let Some(then) = app.ui.windows.unsaved.clone() else { return }; + let Some(pending) = app.ui.windows.unsaved.clone() else { return }; + let mut open = true; - let mut save = None; + let mut save_first = None; let mut cancel = false; - let name: [(&str, &dyn std::fmt::Display); 1] = [("name", &app.session.doc.project.name)]; - let question = - if then == Unsaved::Quit { trf("Save the changes to {name} before closing?", &name) } else { trf("Save the changes to {name} first?", &name) }; + let question_args: [(&str, &dyn std::fmt::Display); 1] = [("name", &app.session.doc.project.name)]; + let question = if pending == Unsaved::Quit { + trf("Save the changes to {name} before closing?", &question_args) + } else { + trf("Save the changes to {name} first?", &question_args) + }; dialog("unsaved", tr("Unsaved changes"), &mut open).show(ctx, |ui| { ui.label(question); ui.add_space(8.0); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.add(primary_button(ui, tr("Save"))).clicked() { - save = Some(true); - } - if ui.button(tr("Don't save")).clicked() { - save = Some(false); - } - if ui.button(tr("Cancel")).clicked() { - cancel = true; - } + + // One row keeps the window to its contents; a bare right-to-left layout fills the screen height + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add(primary_button(ui, tr("Save"))).clicked() { + save_first = Some(true); + } + if ui.button(tr("Don't save")).clicked() { + save_first = Some(false); + } + if ui.button(tr("Cancel")).clicked() { + cancel = true; + } + }); }); }); if !open || cancel { app.ui.windows.unsaved = None; } - match save { + + match save_first { Some(true) => { file_action(app, ctx, "file.save"); } - // Going ahead anyway: the changes are let go. + // Going ahead anyway: the changes are let go Some(false) => app.session.modified = false, None => return, } - // A cancelled or failed save keeps the project and this dialog open. + + // A cancelled or failed save keeps the project and this dialog open if app.session.modified { return; } app.ui.windows.unsaved = None; - match then { + match pending { Unsaved::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close), Unsaved::Command(id) => crate::menus::invoke(app, ctx, &id), #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/tests/close_unsaved.rs b/crates/ui-egui/tests/close_unsaved.rs index 9f518f18..a0c5481d 100644 --- a/crates/ui-egui/tests/close_unsaved.rs +++ b/crates/ui-egui/tests/close_unsaved.rs @@ -90,3 +90,17 @@ fn closing_the_project_with_changes_asks_first() { assert_ne!(name(&h), "Edited", "Don't save closes the project"); assert!(h.state().ui.windows.unsaved.is_none() && !h.state().session.modified); } + +/// The dialog fits one sentence and one button row instead of growing to the screen height +#[test] +fn the_dialog_fits_its_contents() { + // The title bar, one line, one button row and margins take 119 px at 1x and the bug made it 420; the 31 px left over absorbs font and theme tweaks + const MAX_HEIGHT: f32 = 150.0; + + let mut h = harness(true); + request_close(&mut h); + h.run_steps(2); + + let dialog = h.ctx.memory(|m| m.area_rect(egui::Id::unique("unsaved"))).expect("the dialog is shown"); + assert!(dialog.height() < MAX_HEIGHT, "the dialog is {} px tall", dialog.height()); +} From 63df2b56e3ec98f0a80038ea4d86976dffb692bb Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 02:13:28 +0000 Subject: [PATCH 16/73] Shelf hover preview: a big version of the thumbnail Hovering a shelf tile shows a 256 pt preview of the asset over its name, rendered on a long-lived worker (its own thread pool) once the pointer rests on the tile, newest hover first. The smart mask thumbnails and the big mask previews share one bake. Renderers take their size as a parameter; the shelf thumbnails are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lib.rs | 1 + crates/engine/src/mask_preview.rs | 110 +++---- crates/engine/src/mask_preview_camera.rs | 64 +++++ crates/engine/src/preview.rs | 47 +-- crates/ui-egui/src/i18n/ar.rs | 23 -- crates/ui-egui/src/i18n/de.rs | 29 -- crates/ui-egui/src/i18n/es.rs | 29 -- crates/ui-egui/src/i18n/fr.rs | 29 -- crates/ui-egui/src/i18n/it.rs | 29 -- crates/ui-egui/src/i18n/ja.rs | 29 -- crates/ui-egui/src/i18n/ko.rs | 26 -- crates/ui-egui/src/i18n/pt_br.rs | 29 -- crates/ui-egui/src/i18n/zh_hans.rs | 14 - crates/ui-egui/src/lib.rs | 8 +- crates/ui-egui/src/mask_preview_image.rs | 44 +++ crates/ui-egui/src/mask_previews.rs | 104 ------- crates/ui-egui/src/mask_shape.rs | 33 +++ crates/ui-egui/src/preview_image.rs | 168 +++++++++++ crates/ui-egui/src/preview_request.rs | 29 ++ crates/ui-egui/src/preview_worker.rs | 207 +++++++++++++ crates/ui-egui/src/shelf.rs | 119 +++++--- crates/ui-egui/src/shelf_preview.rs | 102 +++++++ crates/ui-egui/src/thumbs.rs | 303 ++++++++------------ crates/ui-egui/src/worker_preview.rs | 13 + crates/ui-egui/tests/shelf_hover_preview.rs | 110 +++++++ 25 files changed, 1065 insertions(+), 634 deletions(-) create mode 100644 crates/engine/src/mask_preview_camera.rs create mode 100644 crates/ui-egui/src/mask_preview_image.rs delete mode 100644 crates/ui-egui/src/mask_previews.rs create mode 100644 crates/ui-egui/src/mask_shape.rs create mode 100644 crates/ui-egui/src/preview_image.rs create mode 100644 crates/ui-egui/src/preview_request.rs create mode 100644 crates/ui-egui/src/preview_worker.rs create mode 100644 crates/ui-egui/src/shelf_preview.rs create mode 100644 crates/ui-egui/src/worker_preview.rs create mode 100644 crates/ui-egui/tests/shelf_hover_preview.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ca7cdeea..201d0eb1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -26,6 +26,7 @@ pub mod layer_ops; pub mod link_cmds; pub mod mask_cmds; pub mod mask_preview; +mod mask_preview_camera; mod mask_preview_pixel; pub mod material_lib; pub mod materials; diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs index e7116d9d..a8e2d1e2 100644 --- a/crates/engine/src/mask_preview.rs +++ b/crates/engine/src/mask_preview.rs @@ -4,15 +4,16 @@ use serde_json::json; use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; -use texturecraft_geom::glam::{Quat, Vec2, Vec3}; -use texturecraft_geom::{primitives, surface_at}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::primitives; +use crate::mask_preview_camera::MaskPreviewCamera; pub use crate::mask_preview_pixel::MaskPreviewPixel; use crate::{EngineError, Result, Session}; /// Texture and bake size of the preview shape in texels (at 256 the edge lines break up). const TEXTURE_PX: u32 = 512; -/// Camera rays per thumbnail pixel along each axis (anti-aliased outline). +/// Camera rays per preview pixel along each axis (anti-aliased outline). const SUPERSAMPLE: usize = 2; /// AO and thickness rays per texel (the default is 64; fewer look the same at thumbnail size). const OCCLUSION_RAYS: u32 = 12; @@ -23,28 +24,20 @@ const CURVATURE_RAYS: u32 = 12; const CURVATURE_RADIUS: f32 = 0.005; /// The mesh maps the smart mask generators read. const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; -/// Camera: looking down by this angle, turned to show the front, left and top panels. -const CAMERA_PITCH_DEG: f32 = 35.0; -const CAMERA_YAW_DEG: f32 = -34.4; +/// Camera views kept at most (one per preview size: the shelf thumbnail and the hover preview). +const CAMERAS_KEPT: usize = 2; -/// What one camera sub-pixel sees: the index of its texel in the preview's texel list and the -/// view-space normal there (None where the ray misses). -type CameraSample = Option<(usize, Vec3)>; - -/// The baked preview shape and what each thumbnail sub-pixel sees. +/// The baked preview shape and, per preview size, what its camera sees. pub struct MaskPreview { session: Session, layer: LayerId, - size: usize, - /// The texels (x, y) the camera sees, each once. - texels: Vec<(u32, u32)>, - /// Per sub-pixel, row-major `(size · SUPERSAMPLE)²`. - samples: Vec, + /// Camera views of the most recently used preview sizes, oldest first (traced on first use). + cameras: Vec, } impl MaskPreview { - /// Bake the preview shape once and aim the camera for `size²` thumbnails. - pub fn new(size: usize) -> Result { + /// Bake the preview shape once (previews of any size reuse it). + pub fn new() -> Result { let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; let set = session.doc.project.texture_set_mut(0)?; set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; @@ -60,27 +53,28 @@ impl MaskPreview { let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; session.bake_now(0, false)?; - let (texels, samples) = camera_samples(&session, size * SUPERSAMPLE); - Ok(MaskPreview { session, layer, size, texels, samples }) + Ok(MaskPreview { session, layer, cameras: Vec::new() }) } - /// Smart mask `id` per thumbnail pixel, row-major `size²`, None where the shape is not seen + /// Smart mask `id` per preview pixel, row-major `size²`, None where the shape is not seen /// (None for an unknown id). - pub fn render(&mut self, id: &str) -> Option>> { + pub fn render(&mut self, id: &str, size: usize) -> Option>> { crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; // Nothing is undone here; the snapshots would pile up over the presets self.session.undo.clear(); - let values = self.session.mask_at(self.layer, &self.texels)?; - let fine = self.size * SUPERSAMPLE; + let camera = camera_for(&mut self.cameras, &self.session, size)?; + let values = self.session.mask_at(self.layer, &camera.texels)?; + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; - let pixels = (0..self.size * self.size) + let pixels = (0..size * size) .map(|i| { - let (x, y) = (i % self.size, i / self.size); + let (x, y) = (i % size, i / size); let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0); for sy in 0..SUPERSAMPLE { for sx in 0..SUPERSAMPLE { - let Some(&Some((texel, n))) = self.samples.get((y * SUPERSAMPLE + sy) * fine + x * SUPERSAMPLE + sx) else { continue }; + let ray = (y * SUPERSAMPLE + sy) * camera.rays_per_side + x * SUPERSAMPLE + sx; + let Some(&Some((texel, n))) = camera.samples.get(ray) else { continue }; mask += values.get(texel).copied().unwrap_or(0.0); normal += n; @@ -94,38 +88,20 @@ impl MaskPreview { } } -/// What each pixel of a `size²` orthographic view of the shape sees: the distinct texels hit, and -/// per pixel (row-major) its sample. -fn camera_samples(session: &Session, size: usize) -> (Vec<(u32, u32)>, Vec) { - let (lo, hi) = session.mesh.bounds(); - let center = (lo + hi) * 0.5; - let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); - let pitch = CAMERA_PITCH_DEG.to_radians(); - let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); - let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); - let right = turn * Vec3::X; - let up = right.cross(forward); - let max_texel = TEXTURE_PX - 1; +/// The camera view for `size²` previews of `session`'s shape, traced on first use (moved to the end +/// of `cameras`); past [`CAMERAS_KEPT`] the least recently used size goes. +fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a MaskPreviewCamera> { + let rays_per_side = size * SUPERSAMPLE; + let camera = match cameras.iter().position(|c| c.rays_per_side == rays_per_side) { + Some(i) => cameras.remove(i), + None => MaskPreviewCamera::new(session, TEXTURE_PX, rays_per_side), + }; + if cameras.len() >= CAMERAS_KEPT { + cameras.remove(0); + } - let mut texels = Vec::new(); - let mut index_of = std::collections::HashMap::new(); - let samples = (0..size * size) - .map(|i| { - let ndc = Vec2::new(((i % size) as f32 + 0.5) / size as f32 * 2.0 - 1.0, 1.0 - ((i / size) as f32 + 0.5) / size as f32 * 2.0); - // Start well outside the shape so every ray enters it from the front - let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; - let hit = session.bvh.closest(origin, forward, radius * 8.0)?; - let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; - let texel = (((surface.uv.x * TEXTURE_PX as f32) as u32).min(max_texel), ((surface.uv.y * TEXTURE_PX as f32) as u32).min(max_texel)); - let index = *index_of.entry(texel).or_insert_with(|| { - texels.push(texel); - texels.len() - 1 - }); - let n = surface.nrm; - Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) - }) - .collect(); - (texels, samples) + cameras.push(camera); + cameras.last() } #[cfg(test)] @@ -139,11 +115,11 @@ mod tests { } #[test] - fn smart_mask_previews_are_in_range_and_tell_edges_from_cavities() { + fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() { let size = 24; - let mut preview = MaskPreview::new(size).unwrap(); + let mut preview = MaskPreview::new().unwrap(); for sm in crate::smart_masks::SMART_MASKS { - let px = preview.render(sm.id).unwrap_or_else(|| panic!("{}", sm.id)); + let px = preview.render(sm.id, size).unwrap_or_else(|| panic!("{}", sm.id)); assert_eq!(px.len(), size * size, "{}", sm.id); assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id); let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect(); @@ -154,10 +130,18 @@ mod tests { } } - let (edges, cavities) = (preview.render("edges_sharp").unwrap(), preview.render("dirt_cavities").unwrap()); + let (edges, cavities) = (preview.render("edges_sharp", size).unwrap(), preview.render("dirt_cavities", size).unwrap()); let shows = |px: &[Option]| px.iter().flatten().any(|p| p.mask > 0.5); assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); - assert!(preview.render("nope").is_none()); + assert!(preview.render("nope", size).is_none()); + + // The same bake renders other sizes, showing the same mask + let big = preview.render("edges_sharp", size * 3).unwrap(); + let mean = |px: &[Option]| px.iter().flatten().map(|p| p.mask).sum::() / px.iter().flatten().count().max(1) as f32; + assert_eq!(big.len(), size * size * 9); + assert!((mean(&big) - mean(&edges)).abs() < 0.05, "{} vs {}", mean(&big), mean(&edges)); + preview.render("edges_sharp", size * 2).unwrap(); + assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); } } diff --git a/crates/engine/src/mask_preview_camera.rs b/crates/engine/src/mask_preview_camera.rs new file mode 100644 index 00000000..9787accb --- /dev/null +++ b/crates/engine/src/mask_preview_camera.rs @@ -0,0 +1,64 @@ +//! The fixed camera of the smart mask previews (see [`crate::mask_preview::MaskPreview`]) at one +//! image size. + +use std::collections::HashMap; + +use texturecraft_geom::glam::{Quat, Vec2, Vec3}; +use texturecraft_geom::surface_at; + +use crate::Session; + +/// Camera: looking down by this angle, turned to show the front, left and top panels. +const CAMERA_PITCH_DEG: f32 = 35.0; +const CAMERA_YAW_DEG: f32 = -34.4; + +/// What one camera ray sees: the index of its texel in [`MaskPreviewCamera::texels`] and the +/// view-space normal there (None where the ray misses). +pub(crate) type CameraSample = Option<(usize, Vec3)>; + +/// What each ray of a square orthographic view of the preview shape sees. +pub(crate) struct MaskPreviewCamera { + /// Rays along each side of the view. + pub rays_per_side: usize, + /// The texels (x, y) the camera sees, each once. + pub texels: Vec<(u32, u32)>, + /// Per ray, row-major `rays_per_side²`. + pub samples: Vec, +} + +impl MaskPreviewCamera { + /// Trace `rays_per_side²` rays at the shape of `session`, whose textures are `texture_px` + /// square. + pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> MaskPreviewCamera { + let (lo, hi) = session.mesh.bounds(); + let center = (lo + hi) * 0.5; + let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); + let pitch = CAMERA_PITCH_DEG.to_radians(); + let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); + let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); + let right = turn * Vec3::X; + let up = right.cross(forward); + let max_texel = texture_px.saturating_sub(1); + + let mut texels = Vec::new(); + let mut index_of = HashMap::new(); + let samples = (0..rays_per_side * rays_per_side) + .map(|i| { + let side = rays_per_side as f32; + let ndc = Vec2::new(((i % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((i / rays_per_side) as f32 + 0.5) / side * 2.0); + // Start well outside the shape so every ray enters it from the front + let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; + let hit = session.bvh.closest(origin, forward, radius * 8.0)?; + let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; + let texel = (((surface.uv.x * texture_px as f32) as u32).min(max_texel), ((surface.uv.y * texture_px as f32) as u32).min(max_texel)); + let index = *index_of.entry(texel).or_insert_with(|| { + texels.push(texel); + texels.len() - 1 + }); + let n = surface.nrm; + Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) + }) + .collect(); + MaskPreviewCamera { rays_per_side, texels, samples } + } +} diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 1dc33631..8882b6d8 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -3,6 +3,7 @@ //! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked //! preview ([`crate::mask_preview`]). +use rayon::prelude::*; use texturecraft_compose::pattern::{Coords, procedural, world_noise}; use texturecraft_core::{ Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, @@ -95,28 +96,34 @@ const CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel:: /// Preview of built-in material `id` (None for an unknown id). pub fn material(id: &str, size: usize) -> Option>> { - let mut p = Project::new("preview", ""); - let layers = build(&mut Builder { p: &mut p, channels: CHANNELS.to_vec() }, id).ok()?; - Some( - sphere_normals(size) - .map(|n| { - let c = coords(n?); - let mut acc = CHANNELS.map(Channel::default_value); - for l in layers.iter().filter(|l| l.visible) { - let LayerKind::Fill(f) = &l.kind else { continue }; - let w = l.mask.as_ref().map_or(1.0, |m| mask(m, &c)); - for (a, ch) in acc.iter_mut().zip(CHANNELS) { - if let (Some(b), Some(v)) = (l.blend(ch), f.sources.get(&ch).and_then(|s| source(s, &f.projection, &c))) { - let t = w * b.opacity.clamp(0.0, 1.0); - *a = [0, 1, 2].map(|k| a[k] + (v[k] - a[k]) * t); - } + let mut project = Project::new("preview", ""); + let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).ok()?; + + // Pixels evaluate independently and big previews take long on one core + let normals: Vec<_> = sphere_normals(size).collect(); + let samples = normals + .into_par_iter() + .map(|normal| { + let at = coords(normal?); + let mut values = CHANNELS.map(Channel::default_value); + for layer in layers.iter().filter(|l| l.visible) { + let LayerKind::Fill(fill) = &layer.kind else { continue }; + + let coverage = layer.mask.as_ref().map_or(1.0, |m| mask(m, &at)); + for (value, channel) in values.iter_mut().zip(CHANNELS) { + let layer_value = fill.sources.get(&channel).and_then(|s| source(s, &fill.projection, &at)); + if let (Some(blend), Some(layer_value)) = (layer.blend(channel), layer_value) { + let weight = coverage * blend.opacity.clamp(0.0, 1.0); + *value = [0, 1, 2].map(|k| value[k] + (layer_value[k] - value[k]) * weight); } } - let [base, metal, rough, height] = acc; - Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] }) - }) - .collect(), - ) + } + + let [base, metal, rough, height] = values; + Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] }) + }) + .collect(); + Some(samples) } /// `f` with its reach in texels multiplied by `k` (previews show at a fraction of 2K). diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 294e8964..6146d6d5 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "شدة الانسداد المحيطي (AO)"), ("About TextureCraft", "حول TextureCraft"), ("About TextureCraft...", "حول TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "إضافة طبقة تعبئة بهذه الصورة (أو اسحبها إلى العرض ثلاثي الأبعاد لوضعها كملصق)", - ), - ("Add a fill layer using this pattern", "إضافة طبقة تعبئة بهذا النمط"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "إضافة طبقة تعبئة بهذه المادة فوق الطبقة المحددة (أو اسحبها إلى مكدس الطبقات)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "أضف نقطة ارتكاز إلى طبقة سفلية لاستخدام مكدسها كقناع."), ("Add anchor point", "إضافة نقطة ارتكاز"), ("Add as decal (view center)", "إضافة كملصق (مركز العرض)"), @@ -51,20 +42,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "إضافة رسم"), ("Add paint layer", "إضافة طبقة رسم"), ("Add smart material from the shelf", "إضافة مادة ذكية من الرف"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "إضافة مجلد المادة الذكية فوق الطبقة المحددة (أو اسحبه إلى مكدس الطبقات)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "إضافة هذه اللمسة النهائية إلى خشونة وارتفاع الطبقة المحددة (أو اسحبها إلى طبقة)", - ), ("Add to the layer content", "إضافة إلى محتوى الطبقة"), ("Add to the mask", "إضافة إلى القناع"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "إضافة إلى محتوى الطبقة المحددة، أو إلى قناعها عند تحديد القناع (أو اسحبها إلى طبقة)", - ), ("Add white mask", "إضافة قناع أبيض"), ("Adjustments", "تعديلات"), ( @@ -663,7 +642,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "التصيير، بتتبع المسار"), ("Replace", "استبدال"), ("Replace Color", "استبدال اللون"), - ("Replace the selected layer's mask with this smart mask (or drag it onto a layer)", "استبدال قناع الطبقة المحددة بهذا القناع الذكي (أو اسحبه إلى طبقة)"), ("Replacement color", "لون الاستبدال"), ("Report a bug...", "الإبلاغ عن خطأ..."), ("Rescan the library folder", "إعادة فحص مجلد المكتبة"), @@ -824,7 +802,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "تراجع"), ("Uniform value", "قيمة موحدة"), ("Use an equirectangular .hdr or .exr image as the environment", "استخدم صورة .hdr أو .exr متساوية المستطيلات كبيئة"), - ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "استخدم كألفا للفرشاة (أو اسحبها إلى منفذ العرض أو خصائص الفرشاة)"), ("Use the control channel or `texturecraft-cli render` for screenshots", "استخدم قناة التحكم أو الأمر `texturecraft-cli render` لالتقاط لقطات الشاشة"), ("Value", "القيمة"), ("Version {version}", "الإصدار {version}"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 3155e6ce..5ceb5dd5 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO-Intensität"), ("About TextureCraft", "Über TextureCraft"), ("About TextureCraft...", "Über TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Füllebene mit diesem Bild hinzufügen (oder in die 3D-Ansicht ziehen, um es als Decal zu platzieren)", - ), - ("Add a fill layer using this pattern", "Füllebene mit diesem Muster hinzufügen"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Füllebene mit diesem Material über der ausgewählten Ebene hinzufügen (oder in den Ebenenstapel ziehen)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Einer darunterliegenden Ebene einen Ankerpunkt hinzufügen, um ihren Stapel als Maske zu verwenden.", @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Malen hinzufügen"), ("Add paint layer", "Malebene hinzufügen"), ("Add smart material from the shelf", "Smart-Material aus der Ablage hinzufügen"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Smart-Material-Ordner über der ausgewählten Ebene hinzufügen (oder in den Ebenenstapel ziehen)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Diese Oberfläche zu Rauheit und Höhe der ausgewählten Ebene hinzufügen (oder auf eine Ebene ziehen)", - ), ("Add to the layer content", "Zum Ebeneninhalt hinzufügen"), ("Add to the mask", "Zur Maske hinzufügen"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Zum Inhalt der ausgewählten Ebene hinzufügen oder zu ihrer Maske, wenn die Maske ausgewählt ist (oder auf eine Ebene ziehen)", - ), ("Add white mask", "Weiße Maske hinzufügen"), ("Adjustments", "Korrekturen"), ( @@ -702,10 +681,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Rendering, Path Tracing"), ("Replace", "Ersetzen"), ("Replace Color", "Farbe ersetzen"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Maske der ausgewählten Ebene durch diese Smart-Maske ersetzen (oder auf eine Ebene ziehen)", - ), ("Replacement color", "Ersatzfarbe"), ("Report a bug...", "Fehler melden..."), ("Rescan the library folder", "Bibliotheksordner neu einlesen"), @@ -866,10 +841,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Rückgängig"), ("Uniform value", "Einheitlicher Wert"), ("Use an equirectangular .hdr or .exr image as the environment", "Ein equirektangulares .hdr- oder .exr-Bild als Umgebung verwenden"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Als Pinsel-Alpha verwenden (oder in das Ansichtsfenster oder die Pinseleigenschaften ziehen)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Für Screenshots den Steuerkanal oder `texturecraft-cli render` verwenden"), ("Value", "Wert"), ("Version {version}", "Version {version}"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 7ba164a9..f9f42e49 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensidad de AO"), ("About TextureCraft", "Acerca de TextureCraft"), ("About TextureCraft...", "Acerca de TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Añadir una capa de relleno con esta imagen (o arrastrarla a la vista 3D para colocarla como calcomanía)", - ), - ("Add a fill layer using this pattern", "Añadir una capa de relleno con este patrón"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Añadir una capa de relleno con este material sobre la capa seleccionada (o arrastrarlo a la pila de capas)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "Añade un punto de anclaje a una capa inferior para usar su pila como máscara."), ("Add anchor point", "Añadir punto de anclaje"), ("Add as decal (view center)", "Añadir como calcomanía (centro de la vista)"), @@ -51,20 +42,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Añadir pintura"), ("Add paint layer", "Añadir capa de pintura"), ("Add smart material from the shelf", "Añadir material inteligente desde la biblioteca"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Añadir la carpeta del material inteligente sobre la capa seleccionada (o arrastrarla a la pila de capas)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Añadir este acabado a la rugosidad y la altura de la capa seleccionada (o arrastrarlo a una capa)", - ), ("Add to the layer content", "Añadir al contenido de la capa"), ("Add to the mask", "Añadir a la máscara"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Añadir al contenido de la capa seleccionada, o a su máscara si está seleccionada (o arrastrarlo a una capa)", - ), ("Add white mask", "Añadir máscara blanca"), ("Adjustments", "Ajustes de imagen"), ( @@ -690,10 +669,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Renderizado con trazado de trayectorias"), ("Replace", "Reemplazar"), ("Replace Color", "Reemplazar color"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Reemplazar la máscara de la capa seleccionada por esta máscara inteligente (o arrastrarla a una capa)", - ), ("Replacement color", "Color de reemplazo"), ("Report a bug...", "Informar de un error..."), ("Rescan the library folder", "Volver a examinar la carpeta de la biblioteca"), @@ -854,10 +829,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Deshacer"), ("Uniform value", "Valor uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Usar una imagen equirrectangular .hdr o .exr como entorno"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Usar como alfa del pincel (o arrastrarlo a la ventana gráfica o a las propiedades del pincel)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Usa el canal de control o `texturecraft-cli render` para las capturas"), ("Value", "Valor"), ("Version {version}", "Versión {version}"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 034d78b5..57c7194f 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -25,15 +25,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensité de l'AO"), ("About TextureCraft", "À propos de TextureCraft"), ("About TextureCraft...", "À propos de TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Ajouter un calque de remplissage avec cette image (ou la glisser sur la vue 3D pour la placer comme décalque)", - ), - ("Add a fill layer using this pattern", "Ajouter un calque de remplissage avec ce motif"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Ajouter un calque de remplissage avec ce matériau au-dessus du calque sélectionné (ou le glisser dans la pile de calques)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Ajoutez un point d'ancrage à un calque inférieur pour utiliser sa pile comme masque.", @@ -57,20 +48,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Ajouter de la peinture"), ("Add paint layer", "Ajouter un calque de peinture"), ("Add smart material from the shelf", "Ajouter un matériau intelligent depuis la bibliothèque"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Ajouter le dossier du matériau intelligent au-dessus du calque sélectionné (ou le glisser dans la pile de calques)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Ajouter cette finition à la rugosité et à la hauteur du calque sélectionné (ou la glisser sur un calque)", - ), ("Add to the layer content", "Ajouter au contenu du calque"), ("Add to the mask", "Ajouter au masque"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Ajouter au contenu du calque sélectionné, ou à son masque si le masque est sélectionné (ou le glisser sur un calque)", - ), ("Add white mask", "Ajouter un masque blanc"), ("Adjustments", "Réglages"), ( @@ -705,10 +684,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Rendu, tracé de chemins"), ("Replace", "Remplacer"), ("Replace Color", "Remplacer la couleur"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Remplacer le masque du calque sélectionné par ce masque intelligent (ou le glisser sur un calque)", - ), ("Replacement color", "Couleur de remplacement"), ("Report a bug...", "Signaler un bug..."), ("Rescan the library folder", "Réanalyser le dossier de la bibliothèque"), @@ -872,10 +847,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Annuler"), ("Uniform value", "Valeur uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Utiliser une image équirectangulaire .hdr ou .exr comme environnement"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Utiliser comme alpha du pinceau (ou le glisser sur la fenêtre d'affichage ou les propriétés du pinceau)", - ), ( "Use the control channel or `texturecraft-cli render` for screenshots", "Utilisez le canal de contrôle ou `texturecraft-cli render` pour les captures d'écran", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 07ce31ea..34abc28a 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensità AO"), ("About TextureCraft", "Informazioni su TextureCraft"), ("About TextureCraft...", "Informazioni su TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Aggiungi un livello di riempimento con questa immagine (o trascinala nella vista 3D per posizionarla come decal)", - ), - ("Add a fill layer using this pattern", "Aggiungi un livello di riempimento con questo motivo"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Aggiungi un livello di riempimento con questo materiale sopra il livello selezionato (o trascinalo nella pila dei livelli)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Aggiungi un punto di ancoraggio a un livello sottostante per usarne la pila come maschera.", @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Aggiungi pittura"), ("Add paint layer", "Aggiungi livello di pittura"), ("Add smart material from the shelf", "Aggiungi un materiale intelligente dalla libreria"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Aggiungi la cartella del materiale intelligente sopra il livello selezionato (o trascinala nella pila dei livelli)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Aggiungi questa finitura alla rugosità e all'altezza del livello selezionato (o trascinala su un livello)", - ), ("Add to the layer content", "Aggiungi al contenuto del livello"), ("Add to the mask", "Aggiungi alla maschera"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Aggiungi al contenuto del livello selezionato, o alla sua maschera se è selezionata (o trascinalo su un livello)", - ), ("Add white mask", "Aggiungi maschera bianca"), ("Adjustments", "Regolazioni"), ( @@ -699,10 +678,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Rendering, path tracing"), ("Replace", "Sostituisci"), ("Replace Color", "Sostituisci colore"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Sostituisci la maschera del livello selezionato con questa maschera intelligente (o trascinala su un livello)", - ), ("Replacement color", "Colore sostitutivo"), ("Report a bug...", "Segnala un bug..."), ("Rescan the library folder", "Ripeti la scansione della cartella della libreria"), @@ -863,10 +838,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Annulla"), ("Uniform value", "Valore uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Usa un'immagine equirettangolare .hdr o .exr come ambiente"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Usa come alpha del pennello (o trascinala nella viewport o nelle proprietà del pennello)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Usa il canale di controllo o `texturecraft-cli render` per gli screenshot"), ("Value", "Valore"), ("Version {version}", "Versione {version}"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index ac768443..2c91d7ce 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -25,15 +25,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO強度"), ("About TextureCraft", "TextureCraftについて"), ("About TextureCraft...", "TextureCraftについて..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "この画像で塗りつぶしレイヤーを追加 (3Dビューにドラッグするとデカールとして配置)", - ), - ("Add a fill layer using this pattern", "このパターンで塗りつぶしレイヤーを追加"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "このマテリアルの塗りつぶしレイヤーを選択中のレイヤーの上に追加 (レイヤースタックへのドラッグも可)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "下のレイヤーにアンカーポイントを追加すると、そのスタックをマスクとして使用できます。", @@ -57,20 +48,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "ペイントを追加"), ("Add paint layer", "ペイントレイヤーを追加"), ("Add smart material from the shelf", "シェルフからスマートマテリアルを追加"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "スマートマテリアルのフォルダーを選択中のレイヤーの上に追加 (レイヤースタックへのドラッグも可)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "この仕上げを選択中のレイヤーのラフネスとハイトに追加 (レイヤーへのドラッグも可)", - ), ("Add to the layer content", "レイヤーのコンテンツに追加"), ("Add to the mask", "マスクに追加"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "選択中のレイヤーのコンテンツ (マスク選択時はマスク) に追加 (レイヤーへのドラッグも可)", - ), ("Add white mask", "白マスクを追加"), ("Adjustments", "色調補正"), ( @@ -681,10 +660,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "パストレースによるレンダリング"), ("Replace", "置換"), ("Replace Color", "色の置き換え"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "選択中のレイヤーのマスクをこのスマートマスクで置換 (レイヤーへのドラッグも可)", - ), ("Replacement color", "置き換え後の色"), ("Report a bug...", "バグを報告..."), ("Rescan the library folder", "ライブラリフォルダーを再スキャン"), @@ -845,10 +820,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "元に戻す"), ("Uniform value", "均一値"), ("Use an equirectangular .hdr or .exr image as the environment", "正距円筒図法の .hdr または .exr 画像を環境として使用"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "ブラシのアルファとして使用 (ビューポートやブラシプロパティへのドラッグも可)", - ), ( "Use the control channel or `texturecraft-cli render` for screenshots", "スクリーンショットにはコントロールチャンネルまたは `texturecraft-cli render` を使用", diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 8fa260be..58a80560 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -25,15 +25,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO 강도"), ("About TextureCraft", "TextureCraft 정보"), ("About TextureCraft...", "TextureCraft 정보..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "이 이미지로 채우기 레이어를 추가합니다 (또는 3D 뷰로 드래그하여 데칼로 배치)", - ), - ("Add a fill layer using this pattern", "이 패턴으로 채우기 레이어를 추가합니다"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "선택한 레이어 위에 이 머티리얼로 채우기 레이어를 추가합니다 (또는 레이어 스택으로 드래그)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "아래 레이어에 앵커 포인트를 추가하면 해당 스택을 마스크로 사용할 수 있습니다."), ("Add anchor point", "앵커 포인트 추가"), ("Add as decal (view center)", "데칼로 추가 (뷰 중앙)"), @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "페인트 추가"), ("Add paint layer", "페인트 레이어 추가"), ("Add smart material from the shelf", "셸프에서 스마트 머티리얼 추가"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "선택한 레이어 위에 스마트 머티리얼 폴더를 추가합니다 (또는 레이어 스택으로 드래그)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "선택한 레이어의 러프니스와 높이에 이 마감을 추가합니다 (또는 레이어로 드래그)", - ), ("Add to the layer content", "레이어 콘텐츠에 추가"), ("Add to the mask", "마스크에 추가"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "선택한 레이어의 콘텐츠에 추가하거나, 마스크가 선택된 경우 마스크에 추가합니다 (또는 레이어로 드래그)", - ), ("Add white mask", "흰색 마스크 추가"), ("Adjustments", "조정"), ( @@ -672,10 +651,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "렌더링, 패스 트레이싱"), ("Replace", "대체"), ("Replace Color", "색상 바꾸기"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "선택한 레이어의 마스크를 이 스마트 마스크로 대체합니다 (또는 레이어로 드래그)", - ), ("Replacement color", "대체 색상"), ("Report a bug...", "버그 신고..."), ("Rescan the library folder", "라이브러리 폴더를 다시 검색합니다"), @@ -836,7 +811,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "실행 취소"), ("Uniform value", "균일 값"), ("Use an equirectangular .hdr or .exr image as the environment", "등장방형 .hdr 또는 .exr 이미지를 환경으로 사용합니다"), - ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "브러시 알파로 사용합니다 (또는 뷰포트나 브러시 속성으로 드래그)"), ("Use the control channel or `texturecraft-cli render` for screenshots", "스크린샷은 제어 채널 또는 `texturecraft-cli render`를 사용하세요"), ("Value", "값"), ("Version {version}", "버전 {version}"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 203a94de..47e49c9c 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensidade de AO"), ("About TextureCraft", "Sobre o TextureCraft"), ("About TextureCraft...", "Sobre o TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Adicionar uma camada de preenchimento com esta imagem (ou arraste-a para a vista 3D para posicioná-la como decalque)", - ), - ("Add a fill layer using this pattern", "Adicionar uma camada de preenchimento com este padrão"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Adicionar uma camada de preenchimento com este material acima da camada selecionada (ou arraste-o para a pilha de camadas)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Adicione um ponto de ancoragem a uma camada abaixo para usar sua pilha como máscara.", @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Adicionar pintura"), ("Add paint layer", "Adicionar camada de pintura"), ("Add smart material from the shelf", "Adicionar material inteligente da prateleira"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Adicionar a pasta do material inteligente acima da camada selecionada (ou arraste-a para a pilha de camadas)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Adicionar este acabamento à rugosidade e à altura da camada selecionada (ou arraste-o para uma camada)", - ), ("Add to the layer content", "Adicionar ao conteúdo da camada"), ("Add to the mask", "Adicionar à máscara"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Adicionar ao conteúdo da camada selecionada, ou à sua máscara quando a máscara estiver selecionada (ou arraste-o para uma camada)", - ), ("Add white mask", "Adicionar máscara branca"), ("Adjustments", "Ajustes"), ( @@ -687,10 +666,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Renderização com path tracing"), ("Replace", "Substituir"), ("Replace Color", "Substituir cor"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Substituir a máscara da camada selecionada por esta máscara inteligente (ou arraste-a para uma camada)", - ), ("Replacement color", "Cor de substituição"), ("Report a bug...", "Relatar um bug..."), ("Rescan the library folder", "Reexaminar a pasta da biblioteca"), @@ -851,10 +826,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Desfazer"), ("Uniform value", "Valor uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Usar uma imagem equirretangular .hdr ou .exr como ambiente"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Usar como alpha do pincel (ou arraste-o para a viewport ou para as propriedades do pincel)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Use o canal de controle ou `texturecraft-cli render` para capturas de tela"), ("Value", "Valor"), ("Version {version}", "Versão {version}"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index d651ba67..8b66aead 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -19,12 +19,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO 强度"), ("About TextureCraft", "关于 TextureCraft"), ("About TextureCraft...", "关于 TextureCraft..."), - ("Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", "使用此图像添加填充图层(或将其拖到 3D 视图中作为贴花放置)"), - ("Add a fill layer using this pattern", "使用此图案添加填充图层"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "在所选图层上方添加使用此材质的填充图层(或将其拖入图层堆栈)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "在下方图层上添加锚点,以将其堆栈用作遮罩。"), ("Add anchor point", "添加锚点"), ("Add as decal (view center)", "添加为贴花(视图中心)"), @@ -45,14 +39,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "添加绘画"), ("Add paint layer", "添加绘画图层"), ("Add smart material from the shelf", "从资产架添加智能材质"), - ("Add the smart material folder above the selected layer (or drag it into the layer stack)", "在所选图层上方添加智能材质文件夹(或将其拖入图层堆栈)"), - ("Add this finish to the selected layer's roughness and height (or drag it onto a layer)", "将此表面处理添加到所选图层的粗糙度和高度(或将其拖到图层上)"), ("Add to the layer content", "添加到图层内容"), ("Add to the mask", "添加到遮罩"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "添加到所选图层的内容,选中遮罩时则添加到遮罩(或将其拖到图层上)", - ), ("Add white mask", "添加白色遮罩"), ("Adjustments", "调整"), ("Aligned: the offset set by the first stroke is kept. V + click sets a new source.", "对齐:保留第一笔设定的偏移。按住 V 并单击可设置新的源。"), @@ -624,7 +612,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "渲染,路径追踪"), ("Replace", "替换"), ("Replace Color", "替换颜色"), - ("Replace the selected layer's mask with this smart mask (or drag it onto a layer)", "用此智能遮罩替换所选图层的遮罩(或将其拖到图层上)"), ("Replacement color", "替换后的颜色"), ("Report a bug...", "报告错误..."), ("Rescan the library folder", "重新扫描库文件夹"), @@ -785,7 +772,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "撤销"), ("Uniform value", "统一值"), ("Use an equirectangular .hdr or .exr image as the environment", "使用等距柱状投影的 .hdr 或 .exr 图像作为环境"), - ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "用作笔刷 Alpha(或将其拖到视口或笔刷属性上)"), ("Use the control channel or `texturecraft-cli render` for screenshots", "截图请使用控制通道或 `texturecraft-cli render`"), ("Value", "值"), ("Version {version}", "版本 {version}"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index df2d1c7a..59c6f40c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,12 +16,17 @@ pub mod fonts; pub mod gpu; pub mod i18n; pub mod keymap; -mod mask_previews; +mod mask_preview_image; +mod mask_shape; pub mod menus; pub mod parity; +mod preview_image; +mod preview_request; +mod preview_worker; pub mod profile; pub mod render_mode; pub mod shelf; +pub mod shelf_preview; pub mod state; pub mod theme; pub mod thumbs; @@ -31,6 +36,7 @@ pub mod viewport; pub mod web_files; pub mod widgets; pub mod windows; +mod worker_preview; use std::sync::Arc; use std::sync::atomic::Ordering; diff --git a/crates/ui-egui/src/mask_preview_image.rs b/crates/ui-egui/src/mask_preview_image.rs new file mode 100644 index 00000000..49fe70f7 --- /dev/null +++ b/crates/ui-egui/src/mask_preview_image.rs @@ -0,0 +1,44 @@ +//! Shading of the smart mask previews: the mask as white over a near-black surface. + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::mask_preview::MaskPreviewPixel; +use texturecraft_engine::texel::linear_to_srgb; + +/// View-space directions of the key light (upper left) and a weaker fill (right), and how much +/// each lights the surface. +const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; +const FILL: [f32; 3] = [0.7, -0.1, 0.7]; +const AMBIENT: f32 = 0.1; +const KEY_STRENGTH: f32 = 0.8; +const FILL_STRENGTH: f32 = 0.35; +/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the +/// shape reads without looking glossy. +const UNMASKED_ALBEDO: f32 = 0.006; +const SHEEN: f32 = 0.1; +const SHEEN_EXPONENT: f32 = 40.0; +/// Where the mask is full: white, darkened at most this much where unlit. +const WHITE_SHADING: f32 = 0.2; + +/// A smart mask preview (sRGB, transparent outside the shape) from preview pixels (row-major +/// `size²`): the mask as white over a near-black surface lit softly from the upper left. No +/// environment reflections. +pub fn mask_preview_image(size: usize, pixels: &[Option]) -> ColorImage { + let key = Vec3::from(KEY).normalize(); + let fill = Vec3::from(FILL).normalize(); + let half = (key + Vec3::Z).normalize(); + let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (out, p) in img.pixels.iter_mut().zip(pixels) { + let Some(p) = p else { continue }; + + let n = p.normal; + let shading = AMBIENT + KEY_STRENGTH * n.dot(key).max(0.0) + FILL_STRENGTH * n.dot(fill).max(0.0); + let unmasked = UNMASKED_ALBEDO * shading + SHEEN * n.dot(half).max(0.0).powf(SHEEN_EXPONENT); + let masked = 1.0 - WHITE_SHADING * (1.0 - shading.min(1.0)); + let linear = unmasked + (masked - unmasked) * p.mask.clamp(0.0, 1.0); + let gray = (linear_to_srgb(linear.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(gray, gray, gray, (p.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + } + img +} diff --git a/crates/ui-egui/src/mask_previews.rs b/crates/ui-egui/src/mask_previews.rs deleted file mode 100644 index fc6018e4..00000000 --- a/crates/ui-egui/src/mask_previews.rs +++ /dev/null @@ -1,104 +0,0 @@ -//! Smart mask shelf thumbnails: every smart mask on the baked preview shape, rendered together on -//! a worker the first time the shelf asks for one (baking the shape takes about two seconds on -//! the CPU; on the web the work runs inline). - -use std::sync::mpsc::{Receiver, TryRecvError}; -use std::time::Duration; - -use egui::{Color32, ColorImage}; -use texturecraft_engine::geom::glam::Vec3; -use texturecraft_engine::mask_preview::{MaskPreview, MaskPreviewPixel}; -use texturecraft_engine::smart_masks::SMART_MASKS; -use texturecraft_engine::texel::linear_to_srgb; - -/// View-space directions of the key light (upper left) and a weaker fill (right), and how much -/// each lights the surface. -const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; -const FILL: [f32; 3] = [0.7, -0.1, 0.7]; -const AMBIENT: f32 = 0.1; -const KEY_STRENGTH: f32 = 0.8; -const FILL_STRENGTH: f32 = 0.35; -/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the -/// shape reads without looking glossy. -const UNMASKED_ALBEDO: f32 = 0.006; -const SHEEN: f32 = 0.1; -const SHEEN_EXPONENT: f32 = 40.0; -/// Where the mask is full: white, darkened at most this much where unlit. -const WHITE_SHADING: f32 = 0.2; -/// How often the shelf checks for the thumbnails while they render. -const POLL: Duration = Duration::from_millis(100); - -/// Smart mask thumbnails by id, as the worker sends them. -type Thumbnails = Vec<(&'static str, ColorImage)>; - -/// Where the smart mask thumbnails are. -#[derive(Default)] -pub enum MaskPreviews { - #[default] - NotStarted, - Rendering(Receiver), - /// Handed out (or the worker failed; the tiles keep their placeholder). - Finished, -} - -impl MaskPreviews { - /// Start rendering `size²` thumbnails on the first call; the finished thumbnails on the call - /// that finds them done (None before and after). - pub fn poll(&mut self, ctx: &egui::Context, size: usize) -> Option { - if matches!(self, MaskPreviews::NotStarted) { - *self = MaskPreviews::Rendering(crate::spawn_worker("texturecraft-mask-previews", move || render(size))); - } - let MaskPreviews::Rendering(rx) = self else { return None }; - - match rx.try_recv() { - Ok(thumbnails) => { - *self = MaskPreviews::Finished; - Some(thumbnails) - } - Err(TryRecvError::Empty) => { - ctx.request_repaint_after(POLL); - None - } - // The worker stopped without a result - Err(TryRecvError::Disconnected) => { - *self = MaskPreviews::Finished; - None - } - } - } -} - -/// Every smart mask's `size²` thumbnail (empty when the preview shape fails to bake). -fn render(size: usize) -> Thumbnails { - let mut preview = match MaskPreview::new(size) { - Ok(p) => p, - Err(e) => { - log::warn!("smart mask previews: {e}"); - return Vec::new(); - } - }; - SMART_MASKS.iter().filter_map(|m| Some((m.id, image(size, &preview.render(m.id)?)))).collect() -} - -/// A thumbnail (sRGB, transparent outside the shape) from preview pixels (row-major `size²`): -/// the mask as white over a near-black surface lit softly from the upper left. No environment -/// reflections. -fn image(size: usize, pixels: &[Option]) -> ColorImage { - let key = Vec3::from(KEY).normalize(); - let fill = Vec3::from(FILL).normalize(); - let half = (key + Vec3::Z).normalize(); - let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); - - for (out, p) in img.pixels.iter_mut().zip(pixels) { - let Some(p) = p else { continue }; - - let n = p.normal; - let shading = AMBIENT + KEY_STRENGTH * n.dot(key).max(0.0) + FILL_STRENGTH * n.dot(fill).max(0.0); - let unmasked = UNMASKED_ALBEDO * shading + SHEEN * n.dot(half).max(0.0).powf(SHEEN_EXPONENT); - let masked = 1.0 - WHITE_SHADING * (1.0 - shading.min(1.0)); - let linear = unmasked + (masked - unmasked) * p.mask.clamp(0.0, 1.0); - let gray = (linear_to_srgb(linear.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8; - *out = Color32::from_rgba_unmultiplied(gray, gray, gray, (p.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); - } - img -} diff --git a/crates/ui-egui/src/mask_shape.rs b/crates/ui-egui/src/mask_shape.rs new file mode 100644 index 00000000..e34c5a7e --- /dev/null +++ b/crates/ui-egui/src/mask_shape.rs @@ -0,0 +1,33 @@ +//! The smart mask preview shape, baked on first use. + +use texturecraft_engine::mask_preview::MaskPreview; + +/// Whether the smart mask preview shape is baked. +#[derive(Default)] +pub enum MaskShape { + #[default] + NotBaked, + /// Boxed: the baked session is large and the enum sits in the worker for its whole life. + Baked(Box), + /// The bake failed; smart mask previews stay empty. + Failed, +} + +impl MaskShape { + /// The baked shape, baking it on the first call (about two seconds; None when it fails). + pub fn get(&mut self) -> Option<&mut MaskPreview> { + if matches!(self, MaskShape::NotBaked) { + *self = match MaskPreview::new() { + Ok(preview) => MaskShape::Baked(Box::new(preview)), + Err(e) => { + log::warn!("smart mask previews: {e}"); + MaskShape::Failed + } + }; + } + match self { + MaskShape::Baked(preview) => Some(preview), + MaskShape::NotBaked | MaskShape::Failed => None, + } + } +} diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs new file mode 100644 index 00000000..3f2321dc --- /dev/null +++ b/crates/ui-egui/src/preview_image.rs @@ -0,0 +1,168 @@ +//! The CPU renderers of the shelf previews at any size: shaded material spheres, procedural +//! swatches, alpha swatches, brush strokes and letterboxed images (no image assets). + +use egui::{Color32, ColorImage}; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; +use texturecraft_engine::paint::{BrushSettings, Shape}; +use texturecraft_engine::preview::{self, Sample}; +use texturecraft_engine::texel::linear_to_srgb; + +/// Pattern scale of the procedural swatches (repeats across the swatch). +const PROCEDURAL_SCALE: f32 = 3.0; +/// Samples per pixel along each axis of the alpha swatches. +const ALPHA_SUPERSAMPLE: usize = 2; + +/// Linear color of a surface with view-space normal `n` and these material values, lit by a key +/// light and a studio environment, seen along +Z. +pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { + let l = [0.45f32, 0.7, 0.55]; + let len = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt(); + let l = l.map(|v| v / len); + let ndl = (n[0] * l[0] + n[1] * l[1] + n[2] * l[2]).max(0.0); + let ndv = n[2].max(0.0); + // View along +Z: half vector between light and view. + let h = [l[0], l[1], l[2] + 1.0]; + let hl = (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt(); + let ndh = ((n[0] * h[0] + n[1] * h[1] + n[2] * h[2]) / hl).max(0.0); + let shin = 2.0 / (rough * rough * rough * rough).max(1e-3) - 2.0; + let spec_amt = ndh.powf(shin.clamp(1.0, 4096.0)) * (shin + 2.0) / 8.0; + // A studio environment seen in the mirror direction: dark floor, bright sky, a horizon that + // blurs (and the whole environment averages out) as roughness grows. + let ry = 2.0 * ndv * n[1]; + let w = 0.06 + rough * 0.9; + let t = ((ry + w) / (2.0 * w)).clamp(0.0, 1.0); + let sharp = 0.04 + 0.03 * (ry + 1.0) + (0.2 + 0.55 * ry.max(0.0)) * t * t * (3.0 - 2.0 * t); + let env = sharp + (0.28 - sharp) * (rough * rough); + let fres = (1.0 - ndv).powi(5); + let sky = 0.35 + 0.25 * n[1]; + let mut out = [0.0; 3]; + for k in 0..3 { + let f0 = 0.04 + (base[k] - 0.04) * metal; + let f = f0 + ((1.0 - rough).max(f0) - f0) * fres; + let diffuse = base[k] * (1.0 - metal) * (ndl * 0.85 + sky * 0.5); + out[k] = diffuse * (1.0 - f) + f * env + f0 * spec_amt * ndl * 1.5; + } + out +} + +/// ACES filmic tone mapping of linear `x` (exposure folded in) to 0..=1. +pub fn aces(x: f32) -> f32 { + let v = x * 0.6; + ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) +} + +/// A shaded sphere image (sRGB, transparent outside) from per-pixel preview samples (row-major +/// `size²`, see [`preview::sphere_normals`]); height bumps the normals. +pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { + let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); + let r = (size as f32 * 0.5 - 1.0).max(0.5); + let h = |x: Option, y: Option| { + let (x, y) = (x.filter(|x| *x < size)?, y?); + samples.get(y.checked_mul(size)?.checked_add(x)?).copied().flatten().map(|s| s.height) + }; + for (i, n) in preview::sphere_normals(size).enumerate() { + let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; + let (x, y) = (i % size, i / size); + let c = s.height; + // Central differences (image y points down). + let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); + let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); + let k = r * 0.5 * 1.5; + let b = [n.x - dx * k, n.y - dy * k, n.z]; + let len = (b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt().max(1e-6); + let col = shade(b.map(|v| v / len), s.base, s.metallic, s.roughness).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0 + 0.5) as u8); + let edge = ((1.0 - (n.x * n.x + n.y * n.y).sqrt()) * r).clamp(0.0, 1.0); + img.pixels[i] = Color32::from_rgba_unmultiplied(col[0], col[1], col[2], (edge * 255.0) as u8); + } + img +} + +/// Grayscale `size²` swatch of procedural `kind`. +pub fn procedural_image(kind: ProceduralKind, size: usize) -> ColorImage { + use texturecraft_engine::compose::pattern::{Coords, procedural}; + use texturecraft_engine::core::{Procedural, Projection}; + use texturecraft_engine::geom::glam::{Vec2, Vec3}; + + let pattern = Procedural { scale: PROCEDURAL_SCALE, ..Procedural::new(kind) }; + let mut img = ColorImage::filled([size, size], Color32::BLACK); + for (i, px) in img.pixels.iter_mut().enumerate() { + let uv = Vec2::new(((i % size) as f32 + 0.5) / size as f32, ((i / size) as f32 + 0.5) / size as f32); + let v = procedural(&pattern, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }); + *px = Color32::from_gray((v.clamp(0.0, 1.0) * 255.0) as u8); + } + img +} + +/// White-on-black `size²` swatch of library alpha `alpha`. +pub fn alpha_image(alpha: &LibraryAlpha, size: usize) -> ColorImage { + let pixels = alpha.render(size, ALPHA_SUPERSAMPLE).into_iter().map(|v| Color32::from_gray((v * 255.0 + 0.5) as u8)).collect(); + ColorImage::new([size, size], pixels) +} + +/// Image resource `img` letterboxed into a `size²` square to keep its proportions, over black +/// where it is transparent. +pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { + let aspect = img.width as f32 / img.height.max(1) as f32; + let (scale_u, scale_v) = if aspect >= 1.0 { (1.0, aspect) } else { (1.0 / aspect.max(1e-6), 1.0) }; + let mut preview = ColorImage::filled([size, size], Color32::BLACK); + for y in 0..size { + for x in 0..size { + let u = ((x as f32 + 0.5) / size as f32 - 0.5) * scale_u + 0.5; + let v = ((y as f32 + 0.5) / size as f32 - 0.5) * scale_v + 0.5; + if !((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)) { + continue; + } + + let sample = img.sample(u, v); + let alpha = sample[3]; + let encode = |c: f32| if img.srgb { (c.clamp(0.0, 1.0) * alpha.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(c * alpha) * 255.0) as u8 }; + preview.pixels[y * size + x] = Color32::from_rgb(encode(sample[0]), encode(sample[1]), encode(sample[2])); + } + } + preview +} + +/// `b`'s stamps (shape, spacing, flow, angle, path following, jitters) along an S curve across +/// an `n`-pixel square, white on black. +pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { + let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); + let radius = n as f32 * 0.11; + let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); + let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); + let mut cover = vec![0f32; n * n]; + // Deterministic jitter per stamp. + let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; + let step = (b.spacing * 2.0 * radius).max(0.5); + let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); + let mut last = curve(0.0); + while t <= 1.0 && i < 2000 { + let p = curve(t); + travelled += (p.0 - last.0).hypot(p.1 - last.1); + last = p; + t += 0.002; + if travelled < step { + continue; + } + travelled = 0.0; + i += 1; + let r = radius * (1.0 - b.jitter_size * rnd(i, 1)); + let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; + let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2); + let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0)); + let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5)); + let (sin, cos) = angle.sin_cos(); + let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n)); + let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n)); + for y in y0..y1 { + for x in x0..x1 { + let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r); + let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow; + let c = &mut cover[y * n + x]; + *c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0)); + } + } + } + ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) +} diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs new file mode 100644 index 00000000..56e2e3b3 --- /dev/null +++ b/crates/ui-egui/src/preview_request.rs @@ -0,0 +1,29 @@ +//! A request to the shelf preview worker (see [`crate::preview_worker::PreviewWorker`]). + +use egui::ColorImage; + +use crate::mask_preview_image::mask_preview_image; +use crate::mask_shape::MaskShape; +use crate::shelf_preview::ShelfPreview; + +/// Render `preview` at `size_px²`; the answer comes back under `key`. +pub struct PreviewRequest { + pub key: String, + pub preview: ShelfPreview, + pub size_px: usize, + /// A hover preview: the worker renders the newest of these before anything else. + // The web renders each request at once, so nothing is reordered there + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub hover: bool, +} + +impl PreviewRequest { + /// The requested image (None for an unknown asset, or a smart mask when the shape fails to + /// bake); smart masks bake `shape` on first use. + pub fn render(&self, shape: &mut MaskShape) -> Option { + match &self.preview { + ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.render(id, self.size_px)?)), + preview => preview.image(self.size_px), + } + } +} diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs new file mode 100644 index 00000000..cf51812e --- /dev/null +++ b/crates/ui-egui/src/preview_worker.rs @@ -0,0 +1,207 @@ +//! Renders shelf previews off the UI thread, on threads of its own (one core is left for the UI): +//! big hover previews and the smart mask thumbnails, which share one baked preview shape. On the web there are no threads: each request renders +//! inline on the UI thread (the window pauses for it). + +#[cfg(target_arch = "wasm32")] +use crate::mask_shape::MaskShape; +use crate::preview_request::PreviewRequest; + +/// A rendered preview: the request's key and its image (None when it could not be rendered). +pub type PreviewResult = (String, Option); + +/// The preview worker, started by the first request. +#[derive(Default)] +pub enum PreviewWorker { + #[default] + NotStarted, + /// The worker thread: requests go in, results come out (it ends when the requests sender is + /// dropped). + #[cfg(not(target_arch = "wasm32"))] + Running { requests: std::sync::mpsc::Sender, results: std::sync::mpsc::Receiver }, + /// The web: requests render as they are made. + #[cfg(target_arch = "wasm32")] + Inline { shape: MaskShape, results: Vec }, + /// The worker could not start or stopped; requests are refused. + // The web has no thread to stop + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + Stopped, +} + +impl PreviewWorker { + /// Queue `request`, starting the worker first if needed; false when the worker is stopped. + /// The worker repaints `ctx` when a result is ready. + pub fn request(&mut self, ctx: &egui::Context, request: PreviewRequest) -> bool { + if matches!(self, PreviewWorker::NotStarted) { + *self = PreviewWorker::start(ctx); + } + + match self { + #[cfg(not(target_arch = "wasm32"))] + PreviewWorker::Running { requests, .. } => { + if requests.send(request).is_ok() { + return true; + } + *self = PreviewWorker::Stopped; + false + } + #[cfg(target_arch = "wasm32")] + PreviewWorker::Inline { shape, results } => { + results.push((request.key.clone(), request.render(shape))); + true + } + PreviewWorker::NotStarted | PreviewWorker::Stopped => false, + } + } + + /// The results ready since the last call. + pub fn poll(&mut self) -> Vec { + match self { + #[cfg(not(target_arch = "wasm32"))] + PreviewWorker::Running { results, .. } => { + use std::sync::mpsc::TryRecvError; + + let mut ready = Vec::new(); + loop { + match results.try_recv() { + Ok(result) => ready.push(result), + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + log::warn!("the shelf preview worker stopped"); + *self = PreviewWorker::Stopped; + break; + } + } + } + ready + } + #[cfg(target_arch = "wasm32")] + PreviewWorker::Inline { results, .. } => std::mem::take(results), + PreviewWorker::NotStarted | PreviewWorker::Stopped => Vec::new(), + } + } + + /// Whether the worker stopped: it refuses requests and answers none of the queued ones. + pub fn is_stopped(&self) -> bool { + matches!(self, PreviewWorker::Stopped) + } + + /// Start the worker thread (Stopped when it cannot start). + #[cfg(not(target_arch = "wasm32"))] + fn start(ctx: &egui::Context) -> PreviewWorker { + use std::collections::VecDeque; + use std::sync::mpsc::channel; + + use crate::mask_shape::MaskShape; + + let (requests, request_rx) = channel::(); + let (result_tx, results) = channel(); + let ctx = ctx.clone(); + let spawned = std::thread::Builder::new().name("texturecraft-shelf-previews".into()).spawn(move || { + // Its own threads: on the global pool a big render would hold up the UI thread's work + let threads = std::thread::available_parallelism().map_or(1, |n| n.get().saturating_sub(1).max(1)); + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("texturecraft-preview-{i}")).build(); + if let Err(e) = &pool { + log::warn!("shelf previews share the global thread pool: {e}"); + } + let mut shape = MaskShape::default(); + let mut queue = VecDeque::new(); + loop { + // Wait for work, then take in everything sent meanwhile + if queue.is_empty() { + let Ok(request) = request_rx.recv() else { break }; + + queue.push_back(request); + } + queue.extend(request_rx.try_iter()); + + let Some(request) = next_request(&mut queue) else { continue }; + let image = match &pool { + Ok(pool) => pool.install(|| request.render(&mut shape)), + Err(_) => request.render(&mut shape), + }; + if result_tx.send((request.key, image)).is_err() { + break; + } + ctx.request_repaint(); + } + }); + + match spawned { + Ok(_) => PreviewWorker::Running { requests, results }, + Err(e) => { + log::warn!("could not start the shelf preview worker: {e}"); + PreviewWorker::Stopped + } + } + } + + /// Render inline (no threads on the web). + #[cfg(target_arch = "wasm32")] + fn start(_ctx: &egui::Context) -> PreviewWorker { + PreviewWorker::Inline { shape: MaskShape::default(), results: Vec::new() } + } +} + +/// The request to render next: the newest hover preview (the one under the pointer), else the +/// oldest request. +#[cfg(not(target_arch = "wasm32"))] +fn next_request(queue: &mut std::collections::VecDeque) -> Option { + match queue.iter().rposition(|request| request.hover) { + Some(newest_hover) => queue.remove(newest_hover), + None => queue.pop_front(), + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::time::{Duration, Instant}; + + use texturecraft_engine::materials::MATERIALS; + use texturecraft_engine::smart_masks::SMART_MASKS; + + use super::*; + use crate::shelf_preview::ShelfPreview; + + #[test] + fn requests_are_answered_and_unknown_assets_get_none() { + let ctx = egui::Context::default(); + let mut worker = PreviewWorker::default(); + let size_px = 32; + let requests = [ + ("material", ShelfPreview::Material(MATERIALS[0].id)), + ("unknown material", ShelfPreview::Material("nope")), + ("mask", ShelfPreview::SmartMask(SMART_MASKS[0].id)), + ("unknown mask", ShelfPreview::SmartMask("nope")), + ]; + for (key, preview) in requests { + assert!(worker.request(&ctx, PreviewRequest { key: key.into(), preview, size_px, hover: false }), "{key}"); + } + + let mut answers = HashMap::new(); + let start = Instant::now(); + while answers.len() < 4 && start.elapsed() < Duration::from_secs(120) { + answers.extend(worker.poll()); + std::thread::sleep(Duration::from_millis(10)); + } + + for key in ["material", "mask"] { + let image = answers.get(key).and_then(Option::as_ref).unwrap_or_else(|| panic!("{key}: {answers:?}")); + assert_eq!(image.size, [size_px, size_px], "{key}"); + } + for key in ["unknown material", "unknown mask"] { + assert!(matches!(answers.get(key), Some(None)), "{key}: {answers:?}"); + } + assert!(!worker.is_stopped()); + } + + #[test] + fn the_newest_hover_preview_goes_first_then_the_oldest_request() { + let request = |key: &str, hover| PreviewRequest { key: key.into(), preview: ShelfPreview::Material("steel"), size_px: 8, hover }; + let mut queue: std::collections::VecDeque<_> = + [request("thumbnail 1", false), request("old hover", true), request("thumbnail 2", false), request("new hover", true)].into(); + + let order: Vec = std::iter::from_fn(|| next_request(&mut queue)).map(|r| r.key).collect(); + assert_eq!(order, ["new hover", "old hover", "thumbnail 1", "thumbnail 2"]); + } +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 351219b9..27309ca9 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -19,9 +19,32 @@ use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; +use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; +use crate::thumbs::Thumbs; use crate::widgets::{dnd_release, icon_button}; +/// A shelf tile's size in points. +const TILE_WIDTH: f32 = 72.0; +const TILE_HEIGHT: f32 = 86.0; +/// Corner radius of a tile's hover and selection highlights, in points. +const TILE_ROUNDING: f32 = 3.0; +/// The thumbnail's size in a tile and its center below the tile's top, in points. +const THUMBNAIL_SIZE: f32 = 56.0; +const THUMBNAIL_CENTER_Y: f32 = 32.0; +/// A placeholder disc's radius relative to the thumbnail's width. +const PLACEHOLDER_RADIUS: f32 = 0.45; +/// A tile label's font size, its gap below the thumbnail and its total side margin, in points. +const LABEL_FONT_SIZE: f32 = 9.5; +const LABEL_GAP: f32 = 3.0; +const LABEL_MARGIN: f32 = 4.0; +/// The hover preview's size and its gap above the label, in points. +const BIG_PREVIEW_SIZE: f32 = 256.0; +const BIG_PREVIEW_LABEL_GAP: f32 = 4.0; +/// How long the pointer rests on a tile before its big preview renders, in seconds (well inside +/// the popup's delay). +const BIG_PREVIEW_DWELL: f32 = 0.1; + #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum Tab { Materials, @@ -267,13 +290,8 @@ fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter tiles(ui, |ui| { for m in shown.iter().filter(|m| m.category == cat) { let tex = app.thumbs.material(ctx, m.id); - let hint = if m.smart { - tr("Add the smart material folder above the selected layer (or drag it into the layer stack)") - } else { - tr("Add a fill layer with this material above the selected layer (or drag it into the layer stack)") - }; let asset = Asset::Material(m.id); - if tile(ui, tex.as_ref(), m.label, hint, Some(&asset)).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Material(m.id), m.label, Some(&asset)).clicked() { apply(app, &asset); } } @@ -340,8 +358,7 @@ fn smart_masks(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filt for m in shown { let tex = app.thumbs.smart_mask(ctx, m.id); let asset = Asset::SmartMask(m.id); - let hint = tr("Replace the selected layer's mask with this smart mask (or drag it onto a layer)"); - if tile(ui, tex.as_ref(), m.label, hint, Some(&asset)).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::SmartMask(m.id), m.label, Some(&asset)).clicked() { apply(app, &asset); } } @@ -361,13 +378,8 @@ fn filters(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: tiles(ui, |ui| { for f in shown.iter().filter(|f| f.group == group) { let tex = app.thumbs.filter(ctx, f.id); - let hint = if f.mask { - tr("Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)") - } else { - tr("Add this finish to the selected layer's roughness and height (or drag it onto a layer)") - }; let asset = Asset::Filter(f.id); - if tile(ui, tex.as_ref(), tr(f.label), hint, Some(&asset)).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Filter(f.id), tr(f.label), Some(&asset)).clicked() { apply(app, &asset); } } @@ -386,7 +398,7 @@ fn brushes(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: tiles(ui, |ui| { for p in shown.iter().filter(|p| p.category == cat) { let tex = app.thumbs.brush_preset(ctx, p); - if tile(ui, tex.as_ref(), p.label, tr("Use this brush (keeps its size)"), None).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Brush(p), p.label, None).clicked() { app.run("brush.preset.apply", json!({"preset": p.id})); } } @@ -467,9 +479,9 @@ fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, fi for &a in shown.iter().filter(|a| a.category == cat) { let tex = app.thumbs.alpha(ctx, a); let asset = Asset::Alpha(&a.id); - let r = tile(ui, tex.as_ref(), &a.label, tr("Use as the brush alpha (or drag it onto the viewport or brush properties)"), Some(&asset)); + let r = tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Alpha(a), &a.label, Some(&asset)); if current.as_deref() == Some(a.id.as_str()) { - ui.painter().rect_stroke(r.rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + ui.painter().rect_stroke(r.rect, TILE_ROUNDING, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); } if r.clicked() { apply(app, &asset); @@ -488,7 +500,7 @@ fn procedurals(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filt tiles(ui, |ui| { for k in shown { let tex = app.thumbs.procedural(ctx, k); - if tile(ui, tex.as_ref(), tr(k.label()), tr("Add a fill layer using this pattern"), None).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Procedural(k), tr(k.label()), None).clicked() { app.run("layer.add.fill", json!({"name": k.label()})); app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": k.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); } @@ -531,7 +543,8 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: let Some(img) = app.session.images.get(&name).cloned() else { continue }; let tex = app.thumbs.image(ctx, &name, &img); let asset = Asset::Texture(name.clone()); - let r = tile(ui, Some(&tex), &name, tr("Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)"), Some(&asset)); + let preview = || ShelfPreview::Image(name.clone(), img); + let r = tile(ui, &mut app.thumbs, Some(&tex), preview, &name, Some(&asset)); if r.clicked() { apply(app, &asset); } @@ -550,32 +563,74 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: } /// A shelf tile: thumbnail (a placeholder disc while it renders) and a wrapped label; tiles with -/// a `drag` asset can be dragged. -fn tile(ui: &mut Ui, tex: Option<&egui::TextureHandle>, label: &str, hint: &str, drag: Option<&Asset>) -> egui::Response { +/// a `drag` asset can be dragged. Hovering shows a big `preview` (made only then) over the label. +fn tile( + ui: &mut Ui, + thumbs: &mut Thumbs, + tex: Option<&egui::TextureHandle>, + preview: impl FnOnce() -> ShelfPreview, + label: &str, + drag: Option<&Asset>, +) -> egui::Response { let tk = Tokens::get(ui.ctx()); let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() }; - let (rect, resp) = ui.allocate_exact_size(vec2(72.0, 86.0), sense); + let (rect, resp) = ui.allocate_exact_size(vec2(TILE_WIDTH, TILE_HEIGHT), sense); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); if let Some(asset) = drag && resp.drag_started() { resp.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() }); } - let p = ui.painter(); + + let painter = ui.painter(); if resp.hovered() || resp.dragged() { - p.rect_filled(rect, 3.0, tk.row_hover); + painter.rect_filled(rect, TILE_ROUNDING, tk.row_hover); } - let img = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, 32.0), vec2(56.0, 56.0)); + let image_rect = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + thumbnail(painter, tex, image_rect, &tk); + let galley = painter.layout(label.to_string(), egui::FontId::proportional(LABEL_FONT_SIZE), tk.text, rect.width() - LABEL_MARGIN); + painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); + + let big = if resp.hovered() { big_preview(ui, thumbs, preview) } else { None }; + resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) +} + +/// A hovered tile's big preview: requested once the pointer has rested [`BIG_PREVIEW_DWELL`], so +/// it renders during the popup's delay but not for tiles the pointer sweeps across (None until the +/// worker renders it). +fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPreview) -> Option { + let ctx = ui.ctx(); + let size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; + let still_for = ui.input(|i| i.pointer.time_since_last_movement()); + if still_for >= BIG_PREVIEW_DWELL { + return thumbs.big(ctx, preview(), size_px); + } + + ctx.request_repaint_after_secs(BIG_PREVIEW_DWELL - still_for); + thumbs.rendered_big(ctx, &preview(), size_px) +} + +/// `tex` drawn into `rect`, or a placeholder disc while it renders. +fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { match tex { Some(t) => { - p.image(t.id(), img, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); + painter.image(t.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); } None => { - p.circle_filled(img.center(), img.width() * 0.45, tk.row_hover); + painter.circle_filled(rect.center(), rect.width() * PLACEHOLDER_RADIUS, tk.row_hover); } } - let galley = p.layout(label.to_string(), egui::FontId::proportional(9.5), tk.text, rect.width() - 4.0); - p.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, img.bottom() + 3.0), galley, tk.text); - resp.on_hover_ui(|ui| { - ui.label(format!("{label}: {hint}")); - }) +} + +/// A tile's hover popup: the `big` preview (the tile's `small` thumbnail scaled up until it +/// renders) over the label. +fn hover_preview(ui: &mut Ui, small: Option<&egui::TextureHandle>, big: Option<&egui::TextureHandle>, label: &str) { + let tk = Tokens::get(ui.ctx()); + ui.set_max_width(BIG_PREVIEW_SIZE); + ui.vertical_centered(|ui| { + let (rect, _) = ui.allocate_exact_size(vec2(BIG_PREVIEW_SIZE, BIG_PREVIEW_SIZE), Sense::hover()); + thumbnail(ui.painter(), big.or(small), rect, &tk); + ui.add_space(BIG_PREVIEW_LABEL_GAP); + ui.label(label); + }); } diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs new file mode 100644 index 00000000..f8cc7e3b --- /dev/null +++ b/crates/ui-egui/src/shelf_preview.rs @@ -0,0 +1,102 @@ +//! What a shelf preview shows, and how to render it at any size. + +use std::sync::Arc; + +use egui::ColorImage; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::paint::BrushSettings; +use texturecraft_engine::paint::alphas::LibraryAlpha; +use texturecraft_engine::paint::presets::BrushPreset; +use texturecraft_engine::preview; + +use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_image, stroke_preview}; + +/// The asset a shelf tile previews. +pub enum ShelfPreview { + /// A built-in material or smart material on a sphere. + Material(&'static str), + /// A smart mask on the baked preview shape (only the preview worker can render it: see + /// [`crate::preview_request::PreviewRequest::render`]). + SmartMask(&'static str), + /// A library filter on a sample material on a sphere. + Filter(&'static str), + /// A procedural pattern as a grayscale swatch. + Procedural(ProceduralKind), + /// A library brush alpha, white on black. + Alpha(&'static LibraryAlpha), + /// A brush preset's stroke along an S curve. + Brush(&'static BrushPreset), + /// An image resource by name. + Image(String, Arc), +} + +impl ShelfPreview { + /// The cache key of the preview (one per asset). + pub fn key(&self) -> String { + match self { + ShelfPreview::Material(id) => format!("mat:{id}"), + ShelfPreview::SmartMask(id) => format!("mask:{id}"), + ShelfPreview::Filter(id) => format!("filter:{id}"), + ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), + ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), + ShelfPreview::Brush(preset) => format!("brush:{}", preset.id), + ShelfPreview::Image(name, _) => format!("image:{name}"), + } + } + + /// The preview as a `size²` image (None for an unknown material or filter id). Smart masks are + /// None here: they need the baked preview shape, which only the preview worker holds, so the + /// UI thread never bakes. + pub fn image(&self, size: usize) -> Option { + match self { + ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), + ShelfPreview::SmartMask(_) => None, + ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), + ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), + ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), + ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)), + ShelfPreview::Image(_, image) => Some(image_preview(image, size)), + } + } +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::filter_lib::FILTERS; + use texturecraft_engine::materials::MATERIALS; + use texturecraft_engine::paint::alphas; + use texturecraft_engine::paint::presets::PRESETS; + + use super::*; + + /// The hover preview's size at 100 % scale. + const BIG_PX: usize = 256; + + #[test] + fn every_tab_renders_a_big_preview() { + let image = ImageRes { width: 4, height: 2, rgba: vec![[0.8, 0.4, 0.2, 1.0]; 8], srgb: true }; + let previews = [ + ShelfPreview::Material(MATERIALS[0].id), + ShelfPreview::Filter(FILTERS[0].id), + ShelfPreview::Procedural(ProceduralKind::ALL[0]), + ShelfPreview::Alpha(&alphas::library()[0]), + ShelfPreview::Brush(&PRESETS[0]), + ShelfPreview::Image("image".into(), Arc::new(image)), + ]; + for preview in previews { + let key = preview.key(); + let image = preview.image(BIG_PX).unwrap_or_else(|| panic!("{key}")); + assert_eq!(image.size, [BIG_PX, BIG_PX], "{key}"); + assert!(image.pixels.iter().any(|c| c.a() > 0 && c.r().max(c.g()).max(c.b()) > 0), "{key}: something shows"); + } + + // The shaded spheres come from finite material values + let finite = |samples: Vec>| { + samples.iter().flatten().all(|s| s.base.iter().chain([&s.metallic, &s.roughness, &s.height]).all(|v| v.is_finite())) + }; + assert!(finite(preview::material(MATERIALS[0].id, BIG_PX).unwrap_or_default())); + assert!(finite(preview::filter(FILTERS[0].id, BIG_PX).unwrap_or_default())); + assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked shape"); + } +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index f5590b31..982caa17 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,95 +1,51 @@ -//! Thumbnails: shaded material spheres, smart masks on a baked preview shape, procedural swatches -//! and brush alpha previews, rendered on the CPU into cached egui textures (no image assets). New -//! shelf thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a -//! frame; the smart mask previews render together on a worker. +//! Thumbnails: shelf previews (see [`crate::preview_image`]) cached as egui textures, plus small +//! shaded spheres and alpha previews drawn as shapes. New shelf thumbnails are rendered lazily, a +//! few per frame, so opening the shelf never stalls a frame; the smart mask thumbnails and the big +//! hover previews render on a worker. -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::paint::presets::BrushPreset; -use texturecraft_engine::paint::{BrushAlpha, BrushSettings, Shape, alphas}; -use texturecraft_engine::preview::{self, Sample}; +use texturecraft_engine::paint::{BrushAlpha, alphas}; use texturecraft_engine::texel::linear_to_srgb; -use crate::mask_previews::MaskPreviews; +use crate::preview_image::{aces, image_preview, shade}; +use crate::preview_request::PreviewRequest; +use crate::preview_worker::PreviewWorker; +use crate::shelf_preview::ShelfPreview; +use crate::worker_preview::WorkerPreview; /// Shelf thumbnails rendered per frame at most (the rest follow on the next frames). const PER_FRAME: usize = 2; -/// Shelf sphere thumbnail size in pixels. +/// Shelf sphere and smart mask thumbnail size in pixels. const SPHERE_PX: usize = 72; +/// Shelf procedural swatch size in pixels. +const PROCEDURAL_PX: usize = 56; +/// Shelf alpha and brush stroke swatch size in pixels. +const SWATCH_PX: usize = 64; +/// Image resource preview size in pixels. +const IMAGE_PX: usize = 64; +/// Big hover previews kept at most (the least recently shown go first). +const BIG_PREVIEWS_KEPT: usize = 32; +/// The shelf's and the brush panel's preview textures. #[derive(Default)] pub struct Thumbs { - /// Shelf thumbnails by key (`mat:`, `mask:`, `filter:`, `proc:`, `alpha:`, - /// `brush:`). + /// Shelf thumbnails by [`ShelfPreview::key`]. shelf: HashMap, images: HashMap, /// (frame, thumbnails rendered in it). budget: (u64, usize), - mask_previews: MaskPreviews, -} - -fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { - let l = [0.45f32, 0.7, 0.55]; - let len = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt(); - let l = l.map(|v| v / len); - let ndl = (n[0] * l[0] + n[1] * l[1] + n[2] * l[2]).max(0.0); - let ndv = n[2].max(0.0); - // View along +Z: half vector between light and view. - let h = [l[0], l[1], l[2] + 1.0]; - let hl = (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt(); - let ndh = ((n[0] * h[0] + n[1] * h[1] + n[2] * h[2]) / hl).max(0.0); - let shin = 2.0 / (rough * rough * rough * rough).max(1e-3) - 2.0; - let spec_amt = ndh.powf(shin.clamp(1.0, 4096.0)) * (shin + 2.0) / 8.0; - // A studio environment seen in the mirror direction: dark floor, bright sky, a horizon that - // blurs (and the whole environment averages out) as roughness grows. - let ry = 2.0 * ndv * n[1]; - let w = 0.06 + rough * 0.9; - let t = ((ry + w) / (2.0 * w)).clamp(0.0, 1.0); - let sharp = 0.04 + 0.03 * (ry + 1.0) + (0.2 + 0.55 * ry.max(0.0)) * t * t * (3.0 - 2.0 * t); - let env = sharp + (0.28 - sharp) * (rough * rough); - let fres = (1.0 - ndv).powi(5); - let sky = 0.35 + 0.25 * n[1]; - let mut out = [0.0; 3]; - for k in 0..3 { - let f0 = 0.04 + (base[k] - 0.04) * metal; - let f = f0 + ((1.0 - rough).max(f0) - f0) * fres; - let diffuse = base[k] * (1.0 - metal) * (ndl * 0.85 + sky * 0.5); - out[k] = diffuse * (1.0 - f) + f * env + f0 * spec_amt * ndl * 1.5; - } - out -} - -fn aces(x: f32) -> f32 { - let v = x * 0.6; - ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) -} - -/// A shaded sphere image (sRGB, transparent outside) from per-pixel preview samples (row-major -/// `size²`, see [`preview::sphere_normals`]); height bumps the normals. -pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { - let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); - let r = (size as f32 * 0.5 - 1.0).max(0.5); - let h = |x: Option, y: Option| { - let (x, y) = (x.filter(|x| *x < size)?, y?); - samples.get(y.checked_mul(size)?.checked_add(x)?).copied().flatten().map(|s| s.height) - }; - for (i, n) in preview::sphere_normals(size).enumerate() { - let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; - let (x, y) = (i % size, i / size); - let c = s.height; - // Central differences (image y points down). - let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); - let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); - let k = r * 0.5 * 1.5; - let b = [n.x - dx * k, n.y - dy * k, n.z]; - let len = (b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt().max(1e-6); - let col = shade(b.map(|v| v / len), s.base, s.metallic, s.roughness).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0 + 0.5) as u8); - let edge = ((1.0 - (n.x * n.x + n.y * n.y).sqrt()) * r).clamp(0.0, 1.0); - img.pixels[i] = Color32::from_rgba_unmultiplied(col[0], col[1], col[2], (edge * 255.0) as u8); - } - img + /// Renders the smart mask thumbnails and the big previews. + worker: PreviewWorker, + /// Worker-rendered previews by [`worker_key`]. + rendered: HashMap, + /// The keys of the big previews in `rendered`, least recently shown first. + big_shown: VecDeque, + /// The frame that last took in the worker's results. + received_in_pass: u64, } impl Thumbs { @@ -114,38 +70,24 @@ impl Thumbs { t } - /// Cached preview of an image resource (64 px, nearest downsample). + /// Cached preview of an image resource (64 px, letterboxed). pub fn image(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { if let Some(t) = self.images.get(name) { return t.clone(); } - let n = 64usize; - // Letterboxed to keep its proportions, over black where it is transparent. - let aspect = img.width as f32 / img.height.max(1) as f32; - let (sx, sy) = if aspect >= 1.0 { (1.0, aspect) } else { (1.0 / aspect.max(1e-6), 1.0) }; - let mut ci = ColorImage::filled([n, n], Color32::BLACK); - for y in 0..n { - for x in 0..n { - let (u, v) = (((x as f32 + 0.5) / n as f32 - 0.5) * sx + 0.5, ((y as f32 + 0.5) / n as f32 - 0.5) * sy + 0.5); - if !((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)) { - continue; - } - let s = img.sample(u, v); - let enc = |c: f32| if img.srgb { (c.clamp(0.0, 1.0) * s[3].clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(c * s[3]) * 255.0) as u8 }; - ci.pixels[y * n + x] = Color32::from_rgb(enc(s[0]), enc(s[1]), enc(s[2])); - } - } - let t = ctx.load_texture(format!("res_{name}"), ci, TextureOptions::LINEAR); + let t = ctx.load_texture(format!("res_{name}"), image_preview(img, IMAGE_PX), TextureOptions::LINEAR); self.images.insert(name.to_string(), t.clone()); t } - /// A cached shelf thumbnail, rendering it with `render` if this frame's budget allows (None - /// until then; a repaint is requested so it follows shortly). - fn shelf(&mut self, ctx: &egui::Context, key: String, render: impl FnOnce() -> ColorImage) -> Option { + /// A cached shelf thumbnail of `preview` at `size_px²`, rendering it if this frame's budget + /// allows (None until then; a repaint is requested so it follows shortly). + fn shelf(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { + let key = preview.key(); if let Some(t) = self.shelf.get(&key) { return Some(t.clone()); } + let frame = ctx.cumulative_pass_nr(); if self.budget.0 != frame { self.budget = (frame, 0); @@ -155,110 +97,117 @@ impl Thumbs { return None; } self.budget.1 += 1; - let t = ctx.load_texture(format!("thumb_{key}"), render(), TextureOptions::LINEAR); + + // An unknown asset shows as an empty thumbnail + let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT)); + let t = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); self.shelf.insert(key, t.clone()); Some(t) } - /// Sphere thumbnail of built-in material `id`. - pub fn material(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("mat:{id}"), || sphere_image(SPHERE_PX, &preview::material(id, SPHERE_PX).unwrap_or_default())) + /// A worker-rendered `size_px²` image of `preview`, requested on the first call (None until it + /// arrives, and for good when it cannot be rendered); `hover` previews jump the worker's queue. + fn worker_rendered(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize, hover: bool) -> Option { + self.receive(ctx); + + let key = worker_key(&preview, size_px); + if !self.rendered.contains_key(&key) { + let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover }); + self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed }); + } + self.ready(&key) } - /// Thumbnail of smart mask `id` on the baked preview shape (None while the thumbnails - /// render; they all arrive together). - pub fn smart_mask(&mut self, ctx: &egui::Context, id: &str) -> Option { - let key = format!("mask:{id}"); - if let Some(t) = self.shelf.get(&key) { - return Some(t.clone()); + /// The worker-rendered preview under `key` if it arrived. + fn ready(&self, key: &str) -> Option { + match self.rendered.get(key) { + Some(WorkerPreview::Ready(t)) => Some(t.clone()), + Some(WorkerPreview::Rendering | WorkerPreview::Failed) | None => None, + } + } + + /// Take in the worker's finished previews, once per frame (dropping the ones no longer + /// wanted). + fn receive(&mut self, ctx: &egui::Context) { + let pass = ctx.cumulative_pass_nr(); + if self.received_in_pass == pass { + return; + } + self.received_in_pass = pass; + + for (key, image) in self.worker.poll() { + let Some(entry) = self.rendered.get_mut(&key) else { continue }; + + *entry = match image { + Some(image) => WorkerPreview::Ready(ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR)), + None => WorkerPreview::Failed, + }; } - for (mask_id, image) in self.mask_previews.poll(ctx, SPHERE_PX).unwrap_or_default() { - let mask_key = format!("mask:{mask_id}"); - let t = ctx.load_texture(format!("thumb_{mask_key}"), image, TextureOptions::LINEAR); - self.shelf.insert(mask_key, t); + // A stopped worker never answers the rest + if self.worker.is_stopped() { + for entry in self.rendered.values_mut().filter(|e| matches!(e, WorkerPreview::Rendering)) { + *entry = WorkerPreview::Failed; + } } - self.shelf.get(&key).cloned() + } + + /// The big hover preview of `preview`, `size_px²` (None until the worker renders it; the + /// least recently shown are dropped past [`BIG_PREVIEWS_KEPT`]). + pub fn big(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { + let key = worker_key(&preview, size_px); + self.big_shown.retain(|k| *k != key); + self.big_shown.push_back(key); + while self.big_shown.len() > BIG_PREVIEWS_KEPT { + if let Some(oldest) = self.big_shown.pop_front() { + self.rendered.remove(&oldest); + } + } + + self.worker_rendered(ctx, preview, size_px, true) + } + + /// The big preview of `preview` if the worker already rendered it (requests nothing). + pub fn rendered_big(&mut self, ctx: &egui::Context, preview: &ShelfPreview, size_px: usize) -> Option { + self.receive(ctx); + self.ready(&worker_key(preview, size_px)) + } + + /// Sphere thumbnail of built-in material `id`. + pub fn material(&mut self, ctx: &egui::Context, id: &'static str) -> Option { + self.shelf(ctx, ShelfPreview::Material(id), SPHERE_PX) + } + + /// Thumbnail of smart mask `id` on the baked preview shape (None while the worker renders + /// it). + pub fn smart_mask(&mut self, ctx: &egui::Context, id: &'static str) -> Option { + self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false) } /// Sphere thumbnail of library filter `id` applied to a sample material. - pub fn filter(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("filter:{id}"), || sphere_image(SPHERE_PX, &preview::filter(id, SPHERE_PX).unwrap_or_default())) + pub fn filter(&mut self, ctx: &egui::Context, id: &'static str) -> Option { + self.shelf(ctx, ShelfPreview::Filter(id), SPHERE_PX) } - /// Grayscale swatch of procedural `k`. - pub fn procedural(&mut self, ctx: &egui::Context, k: ProceduralKind) -> Option { - use texturecraft_engine::compose::pattern::{Coords, procedural}; - use texturecraft_engine::core::{Procedural, Projection}; - use texturecraft_engine::geom::glam::{Vec2, Vec3}; - self.shelf(ctx, format!("proc:{k:?}"), || { - let n = 56usize; - let pr = Procedural { scale: 3.0, ..Procedural::new(k) }; - let mut img = ColorImage::filled([n, n], Color32::BLACK); - for (i, px) in img.pixels.iter_mut().enumerate() { - let uv = Vec2::new(((i % n) as f32 + 0.5) / n as f32, ((i / n) as f32 + 0.5) / n as f32); - let v = procedural(&pr, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }); - *px = Color32::from_gray((v.clamp(0.0, 1.0) * 255.0) as u8); - } - img - }) + /// Grayscale swatch of procedural `kind`. + pub fn procedural(&mut self, ctx: &egui::Context, kind: ProceduralKind) -> Option { + self.shelf(ctx, ShelfPreview::Procedural(kind), PROCEDURAL_PX) } - /// White-on-black swatch of library alpha `a`. - pub fn alpha(&mut self, ctx: &egui::Context, a: &alphas::LibraryAlpha) -> Option { - self.shelf(ctx, format!("alpha:{}", a.id), || { - let n = 64usize; - ColorImage::new([n, n], a.render(n, 2).into_iter().map(|v| Color32::from_gray((v * 255.0 + 0.5) as u8)).collect()) - }) + /// White-on-black swatch of library alpha `alpha`. + pub fn alpha(&mut self, ctx: &egui::Context, alpha: &'static alphas::LibraryAlpha) -> Option { + self.shelf(ctx, ShelfPreview::Alpha(alpha), SWATCH_PX) } /// A brush preset's stroke along an S curve. - pub fn brush_preset(&mut self, ctx: &egui::Context, p: &BrushPreset) -> Option { - self.shelf(ctx, format!("brush:{}", p.id), || stroke_preview(&p.applied(&BrushSettings::default()), 64)) + pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { + self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) } } -/// `b`'s stamps (shape, spacing, flow, angle, path following, jitters) along an S curve across -/// an `n`-pixel square, white on black. -fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { - let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); - let radius = n as f32 * 0.11; - let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); - let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); - let mut cover = vec![0f32; n * n]; - // Deterministic jitter per stamp. - let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; - let step = (b.spacing * 2.0 * radius).max(0.5); - let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); - let mut last = curve(0.0); - while t <= 1.0 && i < 2000 { - let p = curve(t); - travelled += (p.0 - last.0).hypot(p.1 - last.1); - last = p; - t += 0.002; - if travelled < step { - continue; - } - travelled = 0.0; - i += 1; - let r = radius * (1.0 - b.jitter_size * rnd(i, 1)); - let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; - let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2); - let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0)); - let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5)); - let (sin, cos) = angle.sin_cos(); - let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n)); - let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n)); - for y in y0..y1 { - for x in x0..x1 { - let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r); - let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow; - let c = &mut cover[y * n + x]; - *c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0)); - } - } - } - ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) +/// The key of a worker-rendered preview: one per asset and size. +fn worker_key(preview: &ShelfPreview, size_px: usize) -> String { + format!("{}@{size_px}", preview.key()) } /// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews). diff --git a/crates/ui-egui/src/worker_preview.rs b/crates/ui-egui/src/worker_preview.rs new file mode 100644 index 00000000..0252d69f --- /dev/null +++ b/crates/ui-egui/src/worker_preview.rs @@ -0,0 +1,13 @@ +//! A preview rendered by the [`crate::preview_worker::PreviewWorker`], as the thumbnail cache +//! tracks it. + +use egui::TextureHandle; + +/// Where a worker-rendered preview is. +pub enum WorkerPreview { + /// Requested; the worker has not answered yet. + Rendering, + Ready(TextureHandle), + /// The asset is unknown or the worker could not render it (the tile keeps its placeholder). + Failed, +} diff --git a/crates/ui-egui/tests/shelf_hover_preview.rs b/crates/ui-egui/tests/shelf_hover_preview.rs new file mode 100644 index 00000000..4dbaaa7b --- /dev/null +++ b/crates/ui-egui/tests/shelf_hover_preview.rs @@ -0,0 +1,110 @@ +//! Hovering a shelf tile shows a big preview of the asset over its name, rendered once the pointer +//! rests on the tile. + +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf_preview::ShelfPreview; + +/// The shelf's Materials tab. +const MATERIALS_TAB: usize = 0; +/// The hover preview's size in points (pixels at this scale). +const BIG_PREVIEW_SIZE: f32 = 256.0; +/// Simulated seconds per frame, fine enough to stop between the rest and the popup's delay. +const STEP_SECONDS: f32 = 0.001; +/// The popup's delay (egui's tooltip delay) and the rest after which the big preview renders. +const POPUP_DELAY: f32 = 0.5; +const REST: f32 = 0.1; +/// Real time the worker gets to render. +const WORKER_TIMEOUT: Duration = Duration::from_secs(60); + +/// The app on the Materials tab, `step_seconds` per frame, and two materials whose names show +/// nowhere else. +fn materials_shelf(step_seconds: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_step_dt(step_seconds).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.shelf_tab = MATERIALS_TAB; + h.run_steps(4); + + let unique: Vec<_> = MATERIALS.iter().filter(|m| !m.smart && h.query_all_by_label(m.label).count() == 1).take(2).collect(); + assert_eq!(unique.len(), 2, "two materials with unique names"); + (h, unique) +} + +/// The pixel size of the largest texture (not the font atlas) the last frame drew at least +/// `min_width` points wide. +fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_width: f32) -> Option<[usize; 2]> { + let textures = h.ctx.tex_manager(); + let textures = textures.read(); + h.output() + .shapes + .iter() + .filter(|clipped| clipped.shape.texture_id() != egui::TextureId::default() && clipped.shape.visual_bounding_rect().width() >= min_width) + .filter_map(|clipped| textures.meta(clipped.shape.texture_id()).map(|meta| meta.size)) + .max() +} + +/// Whether `material`'s big preview has arrived from the worker (asks for nothing). +fn big_preview_ready(h: &mut Harness<'static, TextureCraftApp>, material: &SmartMaterial) -> bool { + let ctx = h.ctx.clone(); + h.state_mut().thumbs.rendered_big(&ctx, &ShelfPreview::Material(material.id), BIG_PREVIEW_SIZE as usize).is_some() +} + +#[test] +fn hovering_a_shelf_tile_shows_its_big_preview() { + let (mut h, materials) = materials_shelf(1.0 / 4.0); + let material = materials[0]; + let tile = h.get_by_label(material.label).rect(); + assert!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE).is_none(), "nothing big before the hover"); + h.get_by_label(material.label).hover(); + + // The popup's delay, then the worker + let big_px = BIG_PREVIEW_SIZE as usize; + let start = Instant::now(); + while largest_drawn_texture(&h, BIG_PREVIEW_SIZE) != Some([big_px, big_px]) && start.elapsed() < WORKER_TIMEOUT { + h.run_steps(1); + std::thread::sleep(Duration::from_millis(20)); + } + + assert_eq!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE), Some([big_px, big_px]), "the popup draws the big preview"); + // The popup's name sits under the big image, below the tile + let popup_name = h.get_all_by_label(material.label).map(|n| n.rect()).find(|r| r.min.y > tile.max.y).expect("the popup shows the name"); + assert!(popup_name.min.y - tile.max.y >= BIG_PREVIEW_SIZE, "{popup_name:?} under {tile:?}"); +} + +#[test] +fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() { + let (mut h, materials) = materials_shelf(STEP_SECONDS); + let (first, second) = (materials[0], materials[1]); + let (from, to) = (h.get_by_label(first.label).rect().center(), h.get_by_label(second.label).rect().center()); + + // A sweep: the pointer moves every frame across both tiles, then leaves the shelf + let sweep_frames = 40; + for frame in 0..=sweep_frames { + h.hover_at(from.lerp(to, frame as f32 / sweep_frames as f32)); + h.run_steps(1); + } + h.hover_at(egui::pos2(900.0, 500.0)); + h.run_steps(1); + std::thread::sleep(Duration::from_secs(1)); + h.run_steps(1); + assert!(!big_preview_ready(&mut h, first) && !big_preview_ready(&mut h, second), "a sweep renders nothing"); + + // A rest: the preview renders before the popup opens + h.hover_at(from); + h.run_steps((REST * 1.2 / STEP_SECONDS) as usize); + let start = Instant::now(); + let headroom_frames = ((POPUP_DELAY - REST * 1.2) / STEP_SECONDS) as usize - 1; + for _ in 0..headroom_frames { + if big_preview_ready(&mut h, first) || start.elapsed() > WORKER_TIMEOUT { + break; + } + h.run_steps(1); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(big_preview_ready(&mut h, first), "the preview rendered during the popup's delay"); + assert_eq!(h.query_all_by_label(first.label).count(), 1, "the popup is not open yet"); +} From a4b62d6e0895e75085ed4fa406215fa84e6ced70 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 03:05:46 +0000 Subject: [PATCH 17/73] Drop a shelf material on the texture set under the cursor While a material or smart material is dragged over the 3D view, the texture set under the cursor shows its mesh edges in the accent color; a drop selects that set and applies the material there. A drop on the background does nothing. The whole-view outline is gone for materials in the 3D view; image drops, the 2D view and the brush zone are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/file_cmds.rs | 2 +- crates/engine/src/painting.rs | 12 +++- crates/render/src/lib.rs | 2 + crates/render/src/renderer.rs | 106 ++++++++++++++++++++++++---- crates/render/src/set_highlight.rs | 61 ++++++++++++++++ crates/render/src/shaders/mesh.wgsl | 24 ++++++- crates/ui-egui/src/shelf.rs | 52 ++++++++++---- crates/ui-egui/src/viewport.rs | 14 +++- crates/ui-egui/tests/shelf_drop.rs | 72 +++++++++++++++++++ 9 files changed, 308 insertions(+), 37 deletions(-) create mode 100644 crates/render/src/set_highlight.rs create mode 100644 crates/ui-egui/tests/shelf_drop.rs diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 0744aca2..f2b95e03 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -132,7 +132,7 @@ impl Session { fn material_files(&mut self, opts: ExportOptions, tiled: bool, materials: usize) -> Result>> { let opts = ExportOptions { atlas: true, ..opts }; (0..materials) - .map(|m| match self.doc.project.texture_sets.iter().position(|t| t.material == m) { + .map(|m| match self.texture_set_of_material(m) { Some(ts) if tiled || self.doc.project.texture_sets.get(ts).is_some_and(|t| t.tile_grid().is_none()) => self.export_files(&[ts], &opts), _ => Ok(Vec::new()), }) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index de132ffd..6f2a74ff 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -35,6 +35,16 @@ impl Session { pick(&ctx, screen) } + /// The texture set that paints mesh material `material` (a [`SurfaceHit::material`]) + pub fn texture_set_of_material(&self, material: usize) -> Option { + self.doc.project.texture_sets.iter().position(|t| t.material == material) + } + + /// The texture set of the surface under viewport pixel `screen` + pub fn texture_set_at(&self, screen: Vec2, viewport: Vec2) -> Option { + self.pick(screen, viewport).and_then(|hit| self.texture_set_of_material(hit.material)) + } + /// Resolve what a stroke on the selected layer paints into, creating the mask paint effect /// when painting a mask. Must run inside the stroke's history snapshot. fn paint_target(&mut self) -> Result { @@ -560,7 +570,7 @@ impl Session { /// Color picker: copy the material under the cursor into the tool's paint values. pub fn color_pick(&mut self, screen: Vec2, viewport: Vec2) -> Result> { let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; - let ts = self.doc.project.texture_sets.iter().position(|t| t.material == hit.material).unwrap_or(self.ts()); + let ts = self.texture_set_of_material(hit.material).unwrap_or(self.ts()); let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; let (w, h) = (cache.size.0 as f32, cache.size.1 as f32); let (x, y) = ((hit.uv.x * w).clamp(0.0, w - 1.0) as u32, (hit.uv.y * h).clamp(0.0, h - 1.0) as u32); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 01df6c30..c5ca2221 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -23,8 +23,10 @@ pub mod ibl; pub mod mesh_maps; pub mod readback; pub mod renderer; +pub mod set_highlight; mod subdivide; pub mod trace; pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale}; +pub use set_highlight::SetHighlight; pub use wgpu; diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index ea4757d5..4ce9dac3 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -32,6 +32,7 @@ use texturecraft_texel::TILE; use crate::gpu_trace::{Checked, checked}; use crate::ibl; +use crate::set_highlight::SetHighlight; use crate::subdivide::{self, Vertex}; pub const MSAA: u32 = 4; @@ -76,6 +77,8 @@ struct GlobalsRaw { fwd: [f32; 4], disp: [f32; 4], refr: [f32; 4], + highlight: [f32; 4], + highlight_shift: [f32; 4], } /// The post pass uniform (see `Post` in post.wgsl). @@ -96,6 +99,15 @@ struct BlitRaw { dst: [f32; 4], } +/// Width of the highlighted set's edge lines, in pixels +const HIGHLIGHT_WIDTH_PX: f32 = 1.5; + +/// Opacity of the highlighted set's edge lines +const HIGHLIGHT_OPACITY: f32 = 0.9; + +/// Copies of each highlight line, shifted diagonally to the four corners of its extra width (`vs_wire_highlight`) +const HIGHLIGHT_SHIFTS: u32 = 4; + /// How the material is shaded (from the project's display settings and the view mode). #[derive(Clone, Copy, Debug, PartialEq)] pub struct Shade { @@ -134,6 +146,8 @@ pub struct Shade { pub grain: f32, /// Draw the mesh edges over the shaded 3D view (depth tested). pub wireframe_3d: bool, + /// One texture set's mesh edges in a highlight color over the 3D view (the set under a shelf drag) + pub highlight: Option, /// Specular/glossiness shading: base color is the diffuse color and the Specular channel the /// F0 color (roughness arrives as 1 - glossiness from the display conversion). pub spec_gloss: bool, @@ -235,6 +249,7 @@ impl Default for Shade { sharpen: 0.0, grain: 0.0, wireframe_3d: false, + highlight: None, spec_gloss: false, parallax: false, taa: false, @@ -513,6 +528,8 @@ pub struct Renderer { uv_pipeline: wgpu::RenderPipeline, wire_pipeline: wgpu::RenderPipeline, wire3d_pipeline: wgpu::RenderPipeline, + /// The highlighted set's mesh edges, wider and in the highlight color + highlight_pipeline: wgpu::RenderPipeline, bg_pipeline: wgpu::RenderPipeline, blit_pipeline: wgpu::RenderPipeline, post_pipeline: wgpu::RenderPipeline, @@ -886,7 +903,9 @@ impl Renderer { let blend = Some(wgpu::BlendState::ALPHA_BLENDING); let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vb, hdr("fs_wire", blend), MSAA, always()); let wire3d_depth = Some(depth_state(false, wgpu::CompareFunction::LessEqual)); - let wire3d_pipeline = pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vb, hdr("fs_wire3d", blend), MSAA, wire3d_depth); + let wire3d_pipeline = pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vb, hdr("fs_wire3d", blend), MSAA, wire3d_depth.clone()); + let highlight_pipeline = + pipeline(device, "tc_highlight", &layout, &module, "vs_wire_highlight", &vb, hdr("fs_wire_highlight", blend), MSAA, wire3d_depth); let bg_pipeline = pipeline(device, "tc_bg", &bg_layout, &module, "vs_bg", &[], hdr("fs_bg", None), MSAA, always()); let blit_pipeline = pipeline(device, "tc_blit", &blit_layout, &util_module, "vs_blit", &[], Some(("fs_blit", target_format, None)), 1, None); let post_pipeline = pipeline(device, "tc_post", &fx_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); @@ -994,6 +1013,7 @@ impl Renderer { uv_pipeline, wire_pipeline, wire3d_pipeline, + highlight_pipeline, bg_pipeline, blit_pipeline, post_pipeline, @@ -1531,13 +1551,7 @@ impl Renderer { visible: &'a [bool], only: Option, ) -> impl Iterator, &'a SetGpu)> + 'a { - ranges.iter().filter_map(move |&(start, count, material)| { - let ts = self.material_sets.get(material).copied().flatten()?; - if only.is_some_and(|o| o != ts) || !visible.get(ts).copied().unwrap_or(true) { - return None; - } - Some((start..start + count, self.sets.get(ts)?)) - }) + drawable_ranges(ranges, &self.material_sets, visible, only).filter_map(|(range, ts)| Some((range, self.sets.get(ts)?))) } /// Keep the key-light shadow map current; returns its view-projection. `light` points to @@ -1707,6 +1721,8 @@ impl Renderer { fwd: [fwd.x, fwd.y, fwd.z, 0.0], disp, refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0], + highlight: highlight_globals(s, data), + highlight_shift: highlight_shift(frame.size), }; let flag = |b: bool| if b { 1.0 } else { 0.0 }; let post = PostRaw { @@ -1805,7 +1821,7 @@ impl Renderer { /// The scene without transmissive surfaces into `b` (MSAA resolved into mip 0), then its mips. fn behind_pass(&self, encoder: &mut wgpu::CommandEncoder, v: &ViewTargets, b: &Behind, globals_bg: &wgpu::BindGroup, frame: &Frame) { - self.draw_scene(encoder, v, &b.level0, globals_bg, frame, &self.opaque_pipeline, None, &self.refr_black); + self.draw_scene(encoder, v, &b.level0, globals_bg, frame, &self.opaque_pipeline, None, None, &self.refr_black); let Some(pipe) = self.mip_pipelines.get(&self.hdr_format) else { return }; for (dst, bg) in &b.mips { fullscreen(encoder, "tc_behind_mip", dst, CLEAR, pipe, bg); @@ -1869,10 +1885,11 @@ impl Renderer { }; // Transmissive surfaces refract what the behind pass rendered this frame. let refr = v.behind.as_ref().filter(|_| frame.shade.refraction).map_or(&self.refr_black, |b| &b.bg); - self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, refr); + let highlight = frame.shade.highlight.filter(|_| uv_ts.is_none()).map(|highlight| (&self.highlight_pipeline, highlight.set)); + self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, highlight, refr); } - /// One scene pass: background, then the mesh with `pipe` and the wireframe with `wire`. + /// One scene pass: background, then the mesh with `pipe`, the wireframe with `wire` and one set's highlighted edges with `highlight` #[allow(clippy::too_many_arguments)] fn draw_scene( &self, @@ -1883,6 +1900,7 @@ impl Renderer { frame: &Frame, pipe: &wgpu::RenderPipeline, wire: Option<&wgpu::RenderPipeline>, + highlight: Option<(&wgpu::RenderPipeline, usize)>, refr: &wgpu::BindGroup, ) { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { @@ -1912,15 +1930,21 @@ impl Renderer { }; pass.set_bind_group(2, refr, &[]); let geo = self.geometry(m, frame); - // The wireframe draws the mesh's own edges (displaced in the vertex shader too). - for (pipe, vb, ib, ranges) in [(Some(pipe), &geo.vb, &geo.ib, &geo.draws), (wire, &m.geo.vb, &m.lines, &m.line_draws)] { + // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) + let (highlight, highlight_set) = highlight.unzip(); + let passes = [ + (Some(pipe), &geo.vb, &geo.ib, &geo.draws, uv_ts, 1), + (wire, &m.geo.vb, &m.lines, &m.line_draws, uv_ts, 1), + (highlight, &m.geo.vb, &m.lines, &m.line_draws, highlight_set, HIGHLIGHT_SHIFTS), + ]; + for (pipe, vb, ib, ranges, only, instances) in passes { let Some(pipe) = pipe else { continue }; pass.set_pipeline(pipe); pass.set_vertex_buffer(0, vb.slice(..)); pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(ranges, &frame.visible, uv_ts) { + for (range, set) in self.drawable(ranges, &frame.visible, only) { pass.set_bind_group(1, &set.bind_group, &[]); - pass.draw_indexed(range, 0, 0..1); + pass.draw_indexed(range, 0, 0..instances); } } } @@ -1963,6 +1987,39 @@ impl Renderer { } } +/// Index ranges of `ranges` (first, count, material) whose texture set (from `material_sets`) is visible and is `only`, when given, with that set's index +fn drawable_ranges<'a>( + ranges: &'a [(u32, u32, usize)], + material_sets: &'a [Option], + visible: &'a [bool], + only: Option, +) -> impl Iterator, usize)> + 'a { + ranges.iter().filter_map(move |&(start, count, material)| { + let ts = material_sets.get(material).copied().flatten()?; + if only.is_some_and(|o| o != ts) || !visible.get(ts).copied().unwrap_or(true) { + return None; + } + + Some((start..start + count, ts)) + }) +} + +/// Globals `highlight`: the highlight's color and opacity, all zero without one. Data views skip exposure and tone mapping, so they take the color as it is +fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] { + let Some(highlight) = shade.highlight else { return [0.0; 4] }; + + let [r, g, b] = if data { highlight.color } else { highlight.scene_color(shade.exposure_ev, shade.aces) }; + [r, g, b, HIGHLIGHT_OPACITY] +} + +/// Globals `highlight_shift`: how far each of the highlight's line copies moves sideways, in clip units of a `size` pixel target +fn highlight_shift(size: [u32; 2]) -> [f32; 4] { + let half_extra_width = (HIGHLIGHT_WIDTH_PX - 1.0) * 0.5; + let clip_per_pixel = size.map(|pixels| 2.0 / pixels.max(1) as f32); + + [half_extra_width * clip_per_pixel[0], half_extra_width * clip_per_pixel[1], 0.0, 0.0] +} + #[cfg(test)] mod tests { use super::*; @@ -2026,6 +2083,25 @@ mod tests { assert!(!h.renderer.awaiting_gpu()); } + #[test] + fn the_highlight_draws_only_the_highlighted_sets_edges() { + let line_draws = [(0, 4, 0), (4, 6, 1), (10, 2, 2)]; + let material_sets = [Some(0), Some(1), Some(2)]; + let highlighted = |visible: &[bool]| drawable_ranges(&line_draws, &material_sets, visible, Some(1)).collect::>(); + + assert_eq!(highlighted(&[true; 3]), vec![(4..10, 1)]); + assert_eq!(highlighted(&[true, false, true]), vec![], "a hidden set shows no highlight"); + } + + #[test] + fn a_data_view_takes_the_highlight_color_as_it_is() { + let color = [0.8, 0.25, 0.08]; + let shade = Shade { highlight: Some(SetHighlight { set: 0, color }), exposure_ev: 1.0, ..Shade::default() }; + + assert_eq!(highlight_globals(&shade, true), [0.8, 0.25, 0.08, HIGHLIGHT_OPACITY]); + assert_ne!(highlight_globals(&shade, false)[..3], color, "the material view undoes exposure and tone mapping"); + } + #[test] fn a_verdict_that_never_comes_counts_as_a_failure() { let Some((mut h, tx)) = awaiting() else { return }; diff --git a/crates/render/src/set_highlight.rs b/crates/render/src/set_highlight.rs new file mode 100644 index 00000000..878968c1 --- /dev/null +++ b/crates/render/src/set_highlight.rs @@ -0,0 +1,61 @@ +//! A texture set's mesh edges drawn over the 3D view in a highlight color (the set under a shelf drag) + +/// Brightest on-screen value the tone curve can reach without an infinite scene value +const MAX_ACES_SCREEN_VALUE: f32 = 0.99; + +/// Scene scale the post pass applies before its ACES curve (`aces` in post.wgsl) +const ACES_INPUT_SCALE: f32 = 0.6; + +/// Draw texture set `set`'s mesh edges over the 3D view in `color` +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SetHighlight { + pub set: usize, + /// The lines' color on screen, linear RGB + pub color: [f32; 3], +} + +impl SetHighlight { + /// The scene color the lines are drawn with so that exposure `exposure_ev` and the tone curve (ACES when `aces`) show them in [`Self::color`] + pub fn scene_color(&self, exposure_ev: f32, aces: bool) -> [f32; 3] { + let exposure = 2f32.powf(exposure_ev).max(f32::MIN_POSITIVE); + + self.color.map(|screen| { + let screen = screen.max(0.0); + let exposed = if aces { inverse_aces(screen.min(MAX_ACES_SCREEN_VALUE)) } else { screen }; + + exposed / exposure + }) + } +} + +/// The input of post.wgsl's `aces` that gives `screen`: the positive root of its rational curve solved for the input +fn inverse_aces(screen: f32) -> f32 { + let (a, b, c) = (2.43 * screen - 2.51, 0.59 * screen - 0.03, 0.14 * screen); + let scaled = (-b - (b * b - 4.0 * a * c).max(0.0).sqrt()) / (2.0 * a); + + scaled / ACES_INPUT_SCALE +} + +#[cfg(test)] +mod tests { + use super::*; + + /// post.wgsl's `aces` with exposure `exposure_ev` + fn tone_mapped(scene: f32, exposure_ev: f32) -> f32 { + let v = scene * 2f32.powf(exposure_ev) * ACES_INPUT_SCALE; + ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) + } + + #[test] + fn the_scene_color_shows_the_highlight_color_on_screen() { + let highlight = SetHighlight { set: 0, color: [0.9, 0.3, 0.05] }; + for exposure_ev in [-2.0, 0.0, 1.5] { + let scene = highlight.scene_color(exposure_ev, true); + for (scene, screen) in scene.iter().zip(highlight.color) { + assert!((tone_mapped(*scene, exposure_ev) - screen).abs() < 1e-4, "{exposure_ev} EV: {scene} → {screen}"); + } + } + + assert_eq!(highlight.scene_color(1.0, false), [0.45, 0.15, 0.025], "linear: exposure only"); + } +} diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index cd2e8d80..863d6eae 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -24,6 +24,8 @@ struct Globals { fwd: vec4, // xyz camera view direction (unit), w - disp: vec4, // x displacement on (1), y world units per unit of height at strength 1, z vertex spacing in UV units, w - refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w - + highlight: vec4, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity + highlight_shift: vec4, // xy sideways shift of each highlight line copy (clip units), zw - }; @group(0) @binding(0) var g: Globals; @@ -659,8 +661,7 @@ fn fs_wire(i: VOut) -> @location(0) vec4 { // 3D wireframe over the shaded mesh: depth-tested, pulled slightly toward the camera so the // lines win against their own triangles. -@vertex -fn vs_wire3d(v: VIn) -> VOut { +fn wire3d(v: VIn) -> VOut { var o: VOut; o.wpos = v.pos; o.nrm = v.nrm; @@ -671,7 +672,26 @@ fn vs_wire3d(v: VIn) -> VOut { return o; } +@vertex +fn vs_wire3d(v: VIn) -> VOut { + return wire3d(v); +} + @fragment fn fs_wire3d(i: VOut) -> @location(0) vec4 { return vec4(0.35, 0.35, 0.35, 0.45); } + +// The highlighted set's edges: four copies of each line, shifted to the corners of the extra width, make it wider than one pixel +@vertex +fn vs_wire_highlight(v: VIn, @builtin(instance_index) copy: u32) -> VOut { + var o = wire3d(v); + let corner = vec2(f32(copy & 1u), f32((copy >> 1u) & 1u)) * 2.0 - 1.0; + o.clip = vec4(o.clip.xy + corner * g.highlight_shift.xy * o.clip.w, o.clip.zw); + return o; +} + +@fragment +fn fs_wire_highlight(i: VOut) -> @location(0) vec4 { + return g.highlight; +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 351219b9..ea50b11e 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -11,6 +11,7 @@ use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::filter_lib::FILTERS; #[cfg(not(target_arch = "wasm32"))] use texturecraft_engine::formats::mcmat::MCMAT_EXT; +use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::paint::alphas; use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; @@ -119,11 +120,27 @@ pub enum DropZone { Brush, /// The 2D view: alphas and materials. View2d, - /// The 3D view: alphas, materials and textures (placed as decals where they drop). + /// The 3D view: alphas, materials (on the texture set they drop on) and textures (placed as decals where they drop). View3d, } -/// Highlight accepted shelf assets on hover and apply them on drop +/// The texture set under the pointer while a shelf material is dragged over the 3D view `response`: the set a drop there applies it to +pub fn material_drop_set(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { + if app.ui.mode != crate::state::Mode::Painting { + return None; + } + + response.dnd_hover_payload::().filter(|drag| drag.asset.is_material())?; + set_under_pointer(app, ui, response) +} + +/// The texture set of the surface under the pointer in the 3D view `response` +fn set_under_pointer(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { + let local_position = ui.input(|input| input.pointer.interact_pos())? - response.rect.min; + app.session.texture_set_at(Vec2::new(local_position.x, local_position.y), app.session.viewport) +} + +/// Highlight accepted shelf assets on hover and apply them on drop. In the 3D view a material goes to the texture set under the pointer, highlighted by the view itself ([`material_drop_set`]) pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, zone: DropZone) { if app.ui.mode != crate::state::Mode::Painting { return; @@ -136,23 +153,28 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response Asset::Texture(_) => zone == DropZone::View3d, Asset::SmartMask(_) | Asset::Filter(_) => false, }; - if response.dnd_hover_payload::().is_some_and(|drag| accepts(&drag)) { + let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.is_material(); + if response.dnd_hover_payload::().is_some_and(|drag| accepts(&drag) && !onto_set(&drag.asset)) { ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside); } + let pointer = ui.input(|input| input.pointer.interact_pos()); - if let Some(drag) = dnd_release::(response) - && accepts(&drag) - { - match (&drag.asset, pointer) { - (Asset::Texture(name), Some(position)) => { - let (local_position, viewport_size) = (position - response.rect.min, response.rect.size()); - app.run( - "layer.add.decal", - json!({"image": name, "x": local_position.x, "y": local_position.y, "viewport": [viewport_size.x, viewport_size.y]}), - ); - } - (asset, _) => apply(app, asset), + let Some(drag) = dnd_release::(response).filter(|drag| accepts(drag)) else { return }; + + match (&drag.asset, pointer) { + (Asset::Texture(name), Some(position)) => { + let (local_position, viewport_size) = (position - response.rect.min, response.rect.size()); + app.run("layer.add.decal", json!({"image": name, "x": local_position.x, "y": local_position.y, "viewport": [viewport_size.x, viewport_size.y]})); } + // The background takes nothing + (asset, _) if onto_set(asset) => { + let Some(ts) = set_under_pointer(app, ui, response) else { return }; + + if app.run("textureSet.select", json!({"ts": ts})).is_some() { + apply(app, asset); + } + } + (asset, _) => apply(app, asset), } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 78618f1e..4ebe79b3 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -10,7 +10,7 @@ use texturecraft_engine::camera_cmds::DEFAULT_CAMERA; use texturecraft_engine::core::{BakedMap, Channel}; use texturecraft_engine::geom::glam::{Vec2, Vec3}; use texturecraft_engine::{Tool, ViewMode}; -use texturecraft_render::{Frame, Shade, ViewKind}; +use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind}; use crate::TextureCraftApp; use crate::gpu::ViewCallback; @@ -217,6 +217,14 @@ fn shade(app: &TextureCraftApp) -> Shade { } } +/// The texture set a shelf material dragged over the 3D view `response` would drop on, its edges drawn in the accent color +fn drop_highlight(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { + let set = crate::shelf::material_drop_set(app, ui, response)?; + let accent = egui::Rgba::from(Tokens::get(ui.ctx()).viewport_accent); + + Some(SetHighlight { set, color: [accent.r(), accent.g(), accent.b()] }) +} + /// Show what the GPU side reported (each message once while its toast is up). fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) { let names: Vec = reports.memory.iter().filter_map(|ts| app.session.doc.project.texture_sets.get(*ts).map(|t| t.name.clone())).collect(); @@ -565,11 +573,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin size: frame_size_in_pixels(ui, rect), kind: ViewKind::Scene, camera: app.session.camera, - shade: shade(app), + shade: Shade { highlight: drop_highlight(app, ui, &resp), ..shade(app) }, visible: app.session.doc.project.texture_sets.iter().map(|t| t.visible).collect(), }; add_callback(app, ui, rect, frame, sync); - // Shelf drops: a material goes above the selection, an alpha on the brush. + // Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush crate::shelf::drop_target(app, ui, &resp, crate::shelf::DropZone::View3d); // Brush cursor. diff --git a/crates/ui-egui/tests/shelf_drop.rs b/crates/ui-egui/tests/shelf_drop.rs new file mode 100644 index 00000000..5b35cc06 --- /dev/null +++ b/crates/ui-egui/tests/shelf_drop.rs @@ -0,0 +1,72 @@ +//! A shelf material dropped on the 3D view goes to the texture set under the pointer + +use egui::{Event, Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; + +/// Distance between the view points searched for a set or the background +const SEARCH_STEP: f32 = 8.0; + +/// The sample project (Ball = set 0, Base = set 1) with the Ball selected, at 1600 x 960 +fn sample_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + assert_eq!(harness.state().session.ts(), 0); + harness +} + +/// The first point of the 3D view showing texture set `set`, or the background when `None` +fn point_over(harness: &Harness<'_, TextureCraftApp>, set: Option) -> Pos2 { + let app = harness.state(); + let rect = app.viewport_rect; + let steps = |length: f32| (1..(length / SEARCH_STEP) as usize).map(|step| step as f32 * SEARCH_STEP); + + steps(rect.height()) + .flat_map(|y| steps(rect.width()).map(move |x| (x, y))) + .find(|&(x, y)| app.session.texture_set_at(Vec2::new(x, y), app.session.viewport) == set) + .map(|(x, y)| rect.min + egui::vec2(x, y)) + .unwrap() +} + +/// Drop a built-in shelf material at `position`, as a drag from the shelf ends there +fn drop_material(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Material("iron_rusted"), label: "Iron".into() }); + harness.hover_at(position); + harness.run_steps(2); + + harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); +} + +/// Top-level layer count of each texture set +fn stack_sizes(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.doc.project.texture_sets.iter().map(|set| set.stack.len()).collect() +} + +#[test] +fn a_material_dropped_on_another_set_goes_to_that_set_and_selects_it() { + let mut harness = sample_app(); + let before = stack_sizes(&harness); + + let base = point_over(&harness, Some(1)); + drop_material(&mut harness, base); + + assert_eq!(harness.state().session.ts(), 1, "the set under the pointer is selected"); + assert_eq!(stack_sizes(&harness), vec![before[0], before[1] + 1], "only the set under the pointer gets the material"); +} + +#[test] +fn a_material_dropped_on_the_background_changes_nothing() { + let mut harness = sample_app(); + let (stacks, history) = (stack_sizes(&harness), harness.state().session.history_labels().len()); + + let background = point_over(&harness, None); + drop_material(&mut harness, background); + + assert_eq!(harness.state().session.ts(), 0); + assert_eq!(stack_sizes(&harness), stacks); + assert_eq!(harness.state().session.history_labels().len(), history); +} From 747068dbdfa5fd78110a6019881be93439c423c4 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Thu, 5 Nov 2026 21:30:34 -0500 Subject: [PATCH 18/73] Fix bake settings and UV tile controls --- crates/automation/src/headless.rs | 2 +- crates/automation/src/render.rs | 2 +- crates/bake/src/lib.rs | 36 ++- crates/bake/src/test/tile_selection.rs | 54 ++++ crates/bake/src/tests.rs | 5 +- crates/compose/src/baked_maps.rs | 53 +++ crates/compose/src/display.rs | 4 +- crates/compose/src/eval.rs | 17 +- crates/compose/src/lib.rs | 1 + crates/compose/src/store.rs | 37 +-- crates/compose/tests/cache_and_instances.rs | 13 +- crates/core/src/block_scales.rs | 43 +++ crates/core/src/lib.rs | 1 + crates/core/src/project.rs | 31 +- crates/engine/src/bake/bake_task.rs | 15 +- crates/engine/src/bake/layout.rs | 46 +++ .../mesh_map_command.rs} | 50 ++- crates/engine/src/bake/mod.rs | 20 ++ crates/engine/src/bake/model_patch.rs | 40 +++ .../paint_command.rs} | 8 +- crates/engine/src/bake/preserve_tiles.rs | 54 ++++ crates/engine/src/bake/tile_command.rs | 42 +++ crates/engine/src/commands.rs | 3 +- crates/engine/src/inspect.rs | 46 +-- crates/engine/src/lib.rs | 8 +- crates/engine/src/meshmap_cmds.rs | 2 +- crates/engine/src/preview.rs | 1 + crates/engine/src/session.rs | 2 + crates/engine/src/uv_tile_cmds.rs | 145 +++++---- crates/engine/tests/bake_resolution.rs | 130 ++++++++ crates/engine/tests/bake_settings.rs | 112 +++++++ crates/engine/tests/bake_tiles.rs | 172 ++++++++++ crates/engine/tests/udim.rs | 28 +- crates/formats/README.md | 5 + crates/formats/src/export/mod.rs | 4 +- crates/formats/src/project_file/mod.rs | 2 + crates/formats/src/project_file/tests.rs | 20 ++ crates/render/src/mesh_maps.rs | 31 +- crates/ui-egui/src/bake_mode.rs | 112 ------- .../ui-egui/src/bake_mode/common_settings.rs | 15 +- crates/ui-egui/src/bake_mode/map_settings.rs | 27 +- crates/ui-egui/src/bake_mode/mod.rs | 216 +++++++++++++ crates/ui-egui/src/gpu.rs | 10 +- crates/ui-egui/src/i18n/ar.rs | 3 + crates/ui-egui/src/i18n/de.rs | 3 + crates/ui-egui/src/i18n/es.rs | 3 + crates/ui-egui/src/i18n/fr.rs | 3 + crates/ui-egui/src/i18n/it.rs | 3 + crates/ui-egui/src/i18n/ja.rs | 3 + crates/ui-egui/src/i18n/ko.rs | 3 + crates/ui-egui/src/i18n/pt_br.rs | 3 + crates/ui-egui/src/i18n/zh_hans.rs | 3 + crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/tests/bake_mode.rs | 302 +++++++++++++++++- crates/ui-egui/tests/ui_snapshots.rs | 45 +++ docs/control-protocol.md | 33 ++ 56 files changed, 1757 insertions(+), 317 deletions(-) create mode 100644 crates/bake/src/test/tile_selection.rs create mode 100644 crates/compose/src/baked_maps.rs create mode 100644 crates/core/src/block_scales.rs create mode 100644 crates/engine/src/bake/layout.rs rename crates/engine/src/{bake_cmds.rs => bake/mesh_map_command.rs} (90%) create mode 100644 crates/engine/src/bake/model_patch.rs rename crates/engine/src/{bake_paint_cmds.rs => bake/paint_command.rs} (97%) create mode 100644 crates/engine/src/bake/preserve_tiles.rs create mode 100644 crates/engine/src/bake/tile_command.rs create mode 100644 crates/engine/tests/bake_resolution.rs create mode 100644 crates/engine/tests/bake_settings.rs create mode 100644 crates/engine/tests/bake_tiles.rs delete mode 100644 crates/ui-egui/src/bake_mode.rs create mode 100644 crates/ui-egui/src/bake_mode/mod.rs diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 87d58648..0af8274d 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -72,7 +72,7 @@ fn join(dir: &str, name: &str) -> String { impl Headless { pub fn new(session: Session, fs: Filesystem) -> Headless { // Bakes run here (CLI, MCP) cast their rays on the GPU when there is one. - texturecraft_engine::bake_cmds::install_gpu_tracer(std::sync::Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); + texturecraft_engine::bake::install_gpu_tracer(std::sync::Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); Headless { session, fs, gpu: None } } diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index 4621d6a0..c61fce50 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -72,7 +72,7 @@ impl Gpu { // The aux texture behind the mesh-map and mask views (rebuilt every render). let res = texturecraft_render::aux_size(cache.size); let aux = match s.view { - ViewMode::MeshMap(m) => Some(texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res)), + ViewMode::MeshMap(m) => Some(texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res, cache.size, &comp.block_scales)), ViewMode::Mask(id) if s.doc.project.locate(id).is_some_and(|(t, _, _)| t == ts) => s.mask_view_rgba(id, res), _ => None, }; diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 0b315cdb..67c349a4 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -143,14 +143,20 @@ fn alloc(count: usize, value: T) -> Result, BakeError> { } pub fn bake(request: &BakeRequest, progress: &Progress) -> Result { - bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer) + bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, &[]) } /// Retry on the CPU if the supplied tracer fails pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) -> Result { - match bake_in_strips(request, progress, STRIP_TEXELS, tracer) { + bake_tiles(request, progress, &[], Some(tracer)) +} + +/// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing +pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result { + let tracer = tracer.unwrap_or(&CpuTracer); + match bake_in_strips(request, progress, STRIP_TEXELS, tracer, excluded_tiles) { Err(BakeError::Tracer(error)) => { - let mut output = bake(request, progress)?; + let mut output = bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, excluded_tiles)?; output.tracer = format!("CPU ({} unavailable: {error})", tracer.name()); Ok(output) } @@ -160,8 +166,18 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) type OutRow<'a> = Vec<&'a mut [f32]>; -fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usize, tracer: &dyn Tracer) -> Result { +fn bake_in_strips( + request: &BakeRequest, + progress: &Progress, + strip_texels: usize, + tracer: &dyn Tracer, + excluded_tiles: &[(u32, u32)], +) -> Result { validate(request)?; + if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) { + return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into())); + } + let settings = request.settings; let (tile_width, tile_height) = settings.common.output_size(); let tile_size = (tile_width as usize, tile_height as usize); @@ -196,7 +212,17 @@ fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usiz let (sample_start_y, strip_sample_height) = (strip_start * samples_per_axis, rows * samples_per_axis); strip_mesh.uvs = request.mesh.uvs.iter().map(|uv| Vec2::new(uv.x, (uv.y * sample_height as f32 - sample_start_y as f32) / strip_sample_height as f32)).collect(); - let gbuffer = UvGBuffer::new(&strip_mesh, request.material, sample_width as u32, strip_sample_height as u32); + let mut gbuffer = UvGBuffer::new(&strip_mesh, request.material, sample_width as u32, strip_sample_height as u32); + for &(column, row) in excluded_tiles { + let start_x = column as usize * tile_size.0 * samples_per_axis; + let start_y = row as usize * tile_size.1 * samples_per_axis; + let end_y = (start_y + tile_size.1 * samples_per_axis).min(sample_start_y + strip_sample_height); + for sample_y in start_y.max(sample_start_y)..end_y { + let first = (sample_y - sample_start_y) * sample_width + start_x; + gbuffer.tri.get_mut(first..first + tile_size.0 * samples_per_axis).ok_or_else(strip_error)?.fill(NO_TRI); + } + } + let coverage_rows = covered.get_mut(strip_start * width..(strip_start + rows) * width).ok_or_else(strip_error)?; coverage_rows.par_chunks_mut(width).enumerate().for_each(|(row_index, row)| { for (x, covered_pixel) in row.iter_mut().enumerate() { diff --git a/crates/bake/src/test/tile_selection.rs b/crates/bake/src/test/tile_selection.rs new file mode 100644 index 00000000..18f13968 --- /dev/null +++ b/crates/bake/src/test/tile_selection.rs @@ -0,0 +1,54 @@ +use super::{Broken, settings}; +use crate::tracing::CpuTracer; +use crate::{BakeRequest, Progress, bake, bake_in_strips, bake_tiles}; +use texturecraft_core::{BakeAntialiasing, BakedMap, TileGrid}; +use texturecraft_geom::glam::Vec2; +use texturecraft_geom::{Bvh, primitives}; + +#[test] +fn excluded_tiles_match_across_strips_antialiasing_and_cpu_fallback() { + let mut mesh = primitives::udim_plane(); + let grid = TileGrid::of(&[1001, 1002]).unwrap(); + mesh.map_material_uvs(0, |uv| Vec2::from(grid.to_atlas(uv.to_array()))); + let bvh = Bvh::new(&mesh); + let mut settings = settings(32, &[BakedMap::Position, BakedMap::AmbientOcclusion]); + settings.maps.ao.parameters.rays.rays = 4; + settings.common.antialiasing = BakeAntialiasing::Subsampling2x2; + settings.common.dilation = 4; + settings.common.apply_diffusion = true; + let request = BakeRequest { + mesh: &mesh, + bvh: &bvh, + material: 0, + low_base_color: &[], + settings: &settings, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (2, 1), + }; + let full = bake(&request, &Progress::new()).unwrap(); + for excluded in [[(0, 0)], [(1, 0)]] { + let partial = bake_tiles(&request, &Progress::new(), &excluded, None).unwrap(); + let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded).unwrap(); + let fallback = bake_tiles(&request, &Progress::new(), &excluded, Some(&Broken)).unwrap(); + assert_eq!(strips.maps, partial.maps); + assert_eq!(fallback.maps, partial.maps); + assert!(fallback.tracer.contains("Broken unavailable")); + + for map in [BakedMap::Position, BakedMap::AmbientOcclusion] { + let components = map.components(); + for (index, pixel) in partial.maps[&map].chunks_exact(components).enumerate() { + if index % 64 / 32 == excluded[0].0 as usize { + assert_eq!(pixel, &map.neutral()[..components]); + } else { + assert_eq!(pixel, &full.maps[&map][index * components..(index + 1) * components]); + } + } + } + } + + assert!(bake_tiles(&request, &Progress::new(), &[(2, 0)], None).is_err()); + assert!(bake_tiles(&request, &Progress::new(), &[(0, u32::MAX)], None).is_err()); +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 00b46b7b..bb75353e 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -17,6 +17,9 @@ use super::*; #[path = "test/setting.rs"] mod setting; +#[path = "test/tile_selection.rs"] +mod tile_selection; + fn settings(resolution: u32, maps: &[BakedMap]) -> BakeSettings { with_rays( { @@ -307,7 +310,7 @@ fn strips_match_a_single_pass() { tiles: (1, 1), }; let whole = bake(&req, &Progress::new()).unwrap(); - let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer).unwrap(); + let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[]).unwrap(); for (map, a) in &whole.maps { let b = &strips.maps[map]; let off = a.iter().zip(b).filter(|(a, b)| (*a - *b).abs() > 1e-3).count(); diff --git a/crates/compose/src/baked_maps.rs b/crates/compose/src/baked_maps.rs new file mode 100644 index 00000000..1ce05bf7 --- /dev/null +++ b/crates/compose/src/baked_maps.rs @@ -0,0 +1,53 @@ +use std::collections::BTreeMap; + +use texturecraft_core::{BakedMap, BlockScales}; + +/// Dense mesh maps with `components()` floats per texel in row-major order +/// Each UV tile fills its block independently of the working resolution +/// The width is `resolution`; height follows the output size and UV tile grid +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BakedMaps { + /// Width in texels + pub resolution: u32, + pub maps: BTreeMap>>, +} + +impl BakedMaps { + /// Sample a working atlas texel without resampling the stored bake + pub fn sample_working(&self, map: BakedMap, x: u32, y: u32, size: (u32, u32), scales: &BlockScales) -> Option<[f32; 3]> { + let uv = [(x as f32 + 0.5) / size.0.max(1) as f32, (y as f32 + 0.5) / size.1.max(1) as f32]; + self.sample_uv(map, scales.bake_uv(uv, size)?) + } + + /// Nearest sample in the uniform bake atlas + pub fn sample_uv(&self, map: BakedMap, uv: [f32; 2]) -> Option<[f32; 3]> { + if uv.iter().any(|value| !value.is_finite()) { + return None; + } + + let size = (self.resolution, self.height(map)); + self.sample(map, (uv[0] * size.0 as f32) as u32, (uv[1] * size.1 as f32) as u32, size) + } + + /// Height in texels of map `m`, from its length + pub fn height(&self, m: BakedMap) -> u32 { + self.maps.get(&m).map_or(0, |d| (d.len() / (self.resolution.max(1) as usize * m.components())) as u32) + } + + /// Sample the corresponding texel of an image with the supplied output size + pub fn sample(&self, map: BakedMap, x: u32, y: u32, output_size: (u32, u32)) -> Option<[f32; 3]> { + let data = self.maps.get(&map)?; + let width = u64::from(self.resolution.max(1)); + let height = u64::from(self.height(map).max(1)); + let sample_x = (u64::from(x) * width / u64::from(output_size.0.max(1))).min(width - 1); + let sample_y = (u64::from(y) * height / u64::from(output_size.1.max(1))).min(height - 1); + let component_count = map.components(); + let offset = ((sample_y * width + sample_x) as usize).checked_mul(component_count)?; + let texel = data.get(offset..offset.checked_add(component_count)?)?; + Some(if component_count == 3 { [texel[0], texel[1], texel[2]] } else { [texel[0]; 3] }) + } + + pub fn scalar(&self, m: BakedMap, x: u32, y: u32, size: (u32, u32)) -> Option { + self.sample(m, x, y, size).map(|v| v[0]) + } +} diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index f78e9470..ba4b675e 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -159,7 +159,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) }; for i in 0..TILE_AREA { let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let baked_ao = baked.scalar(BakedMap::AmbientOcclusion, x, y, (res, comp.height)).unwrap_or(1.0); + let baked_ao = baked.sample_working(BakedMap::AmbientOcclusion, x, y, (res, comp.height), &comp.block_scales).map_or(1.0, |value| value[0]); let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0); let px = &mut out[i * 4..i * 4 + 4]; px[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; @@ -175,7 +175,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let px = &mut out[i * 4..i * 4 + 4]; // The baked normal is the base the painted normal details sit on (as in export). let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let base = baked.sample(BakedMap::Normal, x, y, (res, comp.height)); + let base = baked.sample_working(BakedMap::Normal, x, y, (res, comp.height), &comp.block_scales); match (n, base) { (Some(t), None) => { for (k, d) in px.iter_mut().take(3).enumerate() { diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index ec75cd97..c5eb4978 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -93,6 +93,7 @@ pub struct Inputs<'a> { pub gbuf: &'a UvGBuffer, pub pixels: &'a PixelStore, pub baked: &'a BakedMaps, + pub block_scales: BlockScales, pub preview: Option<&'a StrokePreview>, /// Imported image resources (fill sources). pub images: &'a ImageStore, @@ -1043,7 +1044,11 @@ impl<'a, 'b> Texel<'a, 'b> { } fn baked(&self, m: BakedMap) -> Option { - self.inp.baked.scalar(m, self.x, self.y, (self.res, self.inp.gbuf.height)) + self.baked_color(m).map(|value| value[0]) + } + + fn baked_color(&self, map: BakedMap) -> Option<[f32; 3]> { + self.inp.baked.sample_working(map, self.x, self.y, (self.res, self.inp.gbuf.height), &self.inp.block_scales) } /// Where projection `proj` samples this texel: the texel's coordinates, or for a decal its @@ -1179,7 +1184,7 @@ impl<'a, 'b> Texel<'a, 'b> { v += (val - v) * o; } EffectKind::ColorSelection { colors, tolerance } => { - let id = self.inp.baked.sample(BakedMap::Id, self.x, self.y, (self.res, self.inp.gbuf.height)); + let id = self.baked_color(BakedMap::Id); let hit = id.is_some_and(|c| colors.iter().any(|k| (k[0] - c[0]).abs().max((k[1] - c[1]).abs()).max((k[2] - c[2]).abs()) <= *tolerance)); let val = if hit { 1.0 } else { 0.0 }; v += (blend1(e.blend, v, val) - v) * o; @@ -1981,7 +1986,7 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u false } }; - let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; + let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); // A field covers the bounding box of the tiles it is built for, which for a scattered sample @@ -2058,7 +2063,7 @@ pub fn flatten_layer(inp: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option< if let Some(l) = solo.layers.get_mut(&id) { l.visible = true; } - let solo_inp = Inputs { project: &solo, preview: None, ..*inp }; + let solo_inp = Inputs { project: &solo, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let fields = neighbourhood_fields(&solo_inp, &channels, tiles); let out: Vec> = tiles .par_iter() @@ -2135,6 +2140,7 @@ mod tests { gbuf: &f.gbuf, pixels: &f.pixels, baked: &f.baked, + block_scales: f.project.texture_sets[0].block_scales(), preview, images: &images, bounds: f.mesh.bounds(), @@ -2252,6 +2258,7 @@ mod tests { gbuf: &fixture.gbuf, pixels: &fixture.pixels, baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), preview: None, images: &images, bounds: fixture.mesh.bounds(), @@ -2606,6 +2613,7 @@ soft {soft:?}" gbuf: &f.gbuf, pixels: &f.pixels, baked: &f.baked, + block_scales: f.project.texture_sets[0].block_scales(), preview: None, images: &images, bounds: f.mesh.bounds(), @@ -2667,6 +2675,7 @@ soft {soft:?}" gbuf: &f.gbuf, pixels: &f.pixels, baked: &f.baked, + block_scales: f.project.texture_sets[0].block_scales(), preview: None, images: &images, bounds: f.mesh.bounds(), diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index ee940e06..01365a27 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -7,6 +7,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod baked_maps; pub mod below; pub mod display; pub mod eval; diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index cf640e0a..1370c0c0 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -1,9 +1,9 @@ //! Pixel data owned by a document: painted layer channels, painted mask effects and baked mesh //! maps. Everything is copy-on-write, so cloning the store for undo is cheap. -use std::collections::{BTreeMap, HashMap}; +use std::collections::HashMap; -use texturecraft_core::{BakedMap, Channel, ChannelKind, LayerId}; +use texturecraft_core::{Channel, ChannelKind, LayerId}; use texturecraft_texel::{TileImage, from_u16, from_u16_signed}; /// Painted data of one paint layer channel: premultiplied value(s) plus coverage, u16 per @@ -56,38 +56,7 @@ pub fn decode(kind: ChannelKind, v: u16) -> f32 { if kind == ChannelKind::Signed { from_u16_signed(v) } else { from_u16(v) } } -/// Baked mesh maps of one texture set (dense, row-major, `components()` floats per texel). The -/// width is `resolution`; height follows the output size and UV tile grid -#[derive(Clone, Debug, Default, PartialEq)] -pub struct BakedMaps { - /// Width in texels. - pub resolution: u32, - pub maps: BTreeMap>>, -} - -impl BakedMaps { - /// Height in texels of map `m` (from its length). - pub fn height(&self, m: BakedMap) -> u32 { - self.maps.get(&m).map_or(0, |d| (d.len() / (self.resolution.max(1) as usize * m.components())) as u32) - } - - /// Sample the corresponding texel of an image with the supplied output size - pub fn sample(&self, map: BakedMap, x: u32, y: u32, output_size: (u32, u32)) -> Option<[f32; 3]> { - let data = self.maps.get(&map)?; - let width = u64::from(self.resolution.max(1)); - let height = u64::from(self.height(map).max(1)); - let sample_x = (u64::from(x) * width / u64::from(output_size.0.max(1))).min(width - 1); - let sample_y = (u64::from(y) * height / u64::from(output_size.1.max(1))).min(height - 1); - let component_count = map.components(); - let offset = ((sample_y * width + sample_x) as usize).checked_mul(component_count)?; - let texel = data.get(offset..offset.checked_add(component_count)?)?; - Some(if component_count == 3 { [texel[0], texel[1], texel[2]] } else { [texel[0]; 3] }) - } - - pub fn scalar(&self, m: BakedMap, x: u32, y: u32, size: (u32, u32)) -> Option { - self.sample(m, x, y, size).map(|v| v[0]) - } -} +pub use crate::baked_maps::BakedMaps; /// A decoded image resource sampled by fills (values in the file's encoding; see `srgb`). #[derive(Clone, Debug, PartialEq)] diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 020a9de0..d7df0258 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -90,7 +90,18 @@ fn heavy_stack(f: &mut Fixture) -> LayerId { } fn inputs<'a>(f: &'a Fixture, ts: usize, images: &'a texturecraft_compose::ImageStore, baked: &'a texturecraft_compose::BakedMaps) -> Inputs<'a> { - Inputs { project: &f.project, ts, mesh: &f.mesh, gbuf: &f.gbuf, pixels: &f.pixels, baked, preview: None, images, bounds: f.mesh.bounds() } + Inputs { + project: &f.project, + ts, + mesh: &f.mesh, + gbuf: &f.gbuf, + pixels: &f.pixels, + baked, + block_scales: f.project.texture_sets[ts].block_scales(), + preview: None, + images, + bounds: f.mesh.bounds(), + } } fn run(f: &Fixture, ts: usize, tiles: &[(u32, u32)], below: Option<&mut BelowCache>) -> Composite { diff --git a/crates/core/src/block_scales.rs b/crates/core/src/block_scales.rs new file mode 100644 index 00000000..65b2403e --- /dev/null +++ b/crates/core/src/block_scales.rs @@ -0,0 +1,43 @@ +/// Per-block UV tile scale for working-to-bake coordinates, filter radii, and height slopes +/// Empty when every tile fills its block; see [`crate::TextureSet::tile_scale`] +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BlockScales { + pub(crate) block: u32, + pub(crate) cols: u32, + pub(crate) scales: Vec, +} + +impl BlockScales { + /// Working atlas UV → uniform bake atlas UV, excluding unused portions of tile blocks + pub fn bake_uv(&self, uv: [f32; 2], working_size: (u32, u32)) -> Option<[f32; 2]> { + if working_size.0 == 0 || working_size.1 == 0 || uv.iter().any(|value| !value.is_finite() || !(0.0..1.0).contains(value)) { + return None; + } + + if self.scales.is_empty() { + return Some(uv); + } + + let block = self.block.max(1) as f32; + let position = [uv[0] * working_size.0 as f32 / block, uv[1] * working_size.1 as f32 / block]; + let origin = position.map(f32::floor); + let scale = self.at((origin[0] * block) as u32, (origin[1] * block) as u32); + let local = [(position[0] - origin[0]) / scale, (position[1] - origin[1]) / scale]; + if local.iter().any(|value| !value.is_finite() || !(0.0..1.0).contains(value)) { + return None; + } + + Some([(origin[0] + local[0]) * block / working_size.0.max(1) as f32, (origin[1] + local[1]) * block / working_size.1.max(1) as f32]) + } + + /// The scale at atlas texel (x, y) + pub fn at(&self, x: u32, y: u32) -> f32 { + let (bx, by) = (x / self.block.max(1), y / self.block.max(1)); + if bx >= self.cols { + return 1.0; + } + + let index = (by as usize).checked_mul(self.cols as usize).and_then(|index| index.checked_add(bx as usize)); + index.and_then(|index| self.scales.get(index)).copied().unwrap_or(1.0) + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index ddaa6045..72adf044 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -9,6 +9,7 @@ pub mod bake; pub mod blend; +mod block_scales; pub mod channel; pub mod layer; pub mod project; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 26d4f6e6..36b5f856 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result}; -pub const FORMAT_VERSION: u32 = 1; +pub const FORMAT_VERSION: u32 = 2; /// Maximum group nesting (also bounds recursion over hostile project files) pub const MAX_DEPTH: usize = 16; @@ -63,6 +63,9 @@ pub struct TextureSet { /// [`TileGrid`], [`TextureSet::block_resolution`] texels square. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub uv_tiles: Vec, + /// UV tiles excluded from baking; missing entries stay included + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub bake_excluded_tiles: BTreeSet, /// Per-tile resolutions overriding `resolution` (UDIM → texels per side). A tile smaller /// than the atlas block fills the block's top-left corner (see [`TextureSet::to_atlas`]). #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] @@ -132,26 +135,7 @@ impl TileGrid { } } -/// The fraction of its atlas block the UV tile of each block fills ([`TextureSet::tile_scale`]): -/// such a tile has fewer texels per UV unit, so filter radii and height slopes shrink with it. -/// Empty (every scale 1) unless a tile is smaller than its block. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct BlockScales { - block: u32, - cols: u32, - scales: Vec, -} - -impl BlockScales { - /// The scale at atlas texel (x, y). - pub fn at(&self, x: u32, y: u32) -> f32 { - let (bx, by) = (x / self.block.max(1), y / self.block.max(1)); - if bx >= self.cols { - return 1.0; - } - self.scales.get(by as usize * self.cols as usize + bx as usize).copied().unwrap_or(1.0) - } -} +pub use crate::block_scales::BlockScales; fn one() -> f32 { 1.0 @@ -176,6 +160,7 @@ impl TextureSet { baked: BTreeSet::new(), visible: true, uv_tiles: Vec::new(), + bake_excluded_tiles: BTreeSet::new(), tile_resolutions: BTreeMap::new(), } } @@ -185,6 +170,10 @@ impl TextureSet { TileGrid::of(&self.uv_tiles) } + pub fn has_enabled_bake_tiles(&self) -> bool { + self.uv_tiles.is_empty() || self.uv_tiles.iter().any(|tile| !self.bake_excluded_tiles.contains(tile)) + } + /// Height strength for slopes measured over the whole texture width (the viewport shader, /// the path tracer): a UV tile atlas is one tile per column wide. pub fn atlas_height_strength(&self) -> f32 { diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index 831a7abc..8c942176 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -1,7 +1,8 @@ use super::MergedHigh; use crate::{EngineError, Result}; use std::sync::Arc; -use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake, bake_on, tracing::Tracer}; +use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer}; +use texturecraft_compose::BakedMaps; use texturecraft_core::BakeSettings; use texturecraft_geom::{Bvh, Mesh}; @@ -20,6 +21,9 @@ pub struct BakeTask { pub cage_paint: Option>, /// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles. pub tiles: (u32, u32), + /// Snapshot of tile selection and pixels to retain while the worker runs + pub excluded_tiles: Vec<(u32, u32)>, + pub previous_maps: BakedMaps, /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`). pub tracer: Option>, } @@ -40,10 +44,9 @@ impl BakeTask { cage_paint: self.cage_paint.as_deref(), tiles: self.tiles, }; - match &self.tracer { - Some(tracer) => bake_on(&request, progress, tracer.as_ref()), - None => bake(&request, progress), - } - .map_err(|e| EngineError::Other(format!("bake failed: {e}"))) + let mut output = bake_tiles(&request, progress, &self.excluded_tiles, self.tracer.as_deref()) + .map_err(|error| EngineError::Other(format!("bake failed: {error}")))?; + super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; + Ok(output) } } diff --git a/crates/engine/src/bake/layout.rs b/crates/engine/src/bake/layout.rs new file mode 100644 index 00000000..70e4b539 --- /dev/null +++ b/crates/engine/src/bake/layout.rs @@ -0,0 +1,46 @@ +use std::sync::Arc; + +use rayon::prelude::*; +use texturecraft_bake::BakePaintMap; +use texturecraft_core::TextureSet; +use texturecraft_geom::glam::Vec2; + +use crate::{EngineError, Result}; + +/// Correction paint stays in working coordinates; the worker reads a uniform bake atlas +pub(super) fn paint_for_bake(painted: &Arc, set: &TextureSet) -> Result> { + let Some(grid) = set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) else { + return Ok(painted.clone()); + }; + + painted.validate().map_err(|error| EngineError::Other(error.to_string()))?; + let (width, height) = (painted.width, painted.height); + let mut values = vec![0.0; painted.values.len()]; + values.par_chunks_mut(width as usize).enumerate().for_each(|(y, row)| { + for (x, value) in row.iter_mut().enumerate() { + let uv = grid.from_atlas([(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32]); + *value = painted.sample(Vec2::from_array(set.to_atlas(&grid, uv, uv))); + } + }); + Ok(Arc::new(BakePaintMap { width, height, values })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn correction_paint_follows_the_same_surface_in_bake_coordinates() { + let mut set = TextureSet::new("Tiles", 0, 256); + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 128); + let mut paint = BakePaintMap::constant(0.0).resized(128, 64).unwrap(); + paint.paint(&[Vec2::new(0.625, 0.25)], 0.05, 1.0, 1.0, 1.0).unwrap(); + let paint = Arc::new(paint); + let baked = paint_for_bake(&paint, &set).unwrap(); + assert!(paint.sample(Vec2::new(0.625, 0.25)) > 0.99); + assert!(baked.sample(Vec2::new(0.75, 0.5)) > 0.99); + assert_eq!(baked.sample(Vec2::new(0.25, 0.5)), 0.0); + assert_eq!(paint.sample(Vec2::new(0.75, 0.5)), 0.0); + } +} diff --git a/crates/engine/src/bake_cmds.rs b/crates/engine/src/bake/mesh_map_command.rs similarity index 90% rename from crates/engine/src/bake_cmds.rs rename to crates/engine/src/bake/mesh_map_command.rs index d56a2bc0..e5982f18 100644 --- a/crates/engine/src/bake_cmds.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -2,6 +2,8 @@ //! high-definition mesh list, the cage, and running a bake. Bakes cast their rays on the GPU //! tracer the app installs ([`install_gpu_tracer`]) and on the CPU otherwise. +use super::model_patch; + use std::collections::BTreeMap; use std::sync::{Arc, OnceLock}; use texturecraft_core::BakePaintTarget; @@ -17,7 +19,7 @@ use texturecraft_core::{ use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; use crate::{EngineError, Result, Session, cmd}; -pub fn specs() -> Vec { +pub(super) fn specs() -> Vec { vec![ cmd!( "bake.run", @@ -33,7 +35,7 @@ pub fn specs() -> Vec { "Bake settings", [], None, - "{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), model?: complete nested BakeSettings (named enum values), preserveEnabled?: keep each texture set enabled flag when replacing the model, resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?: never|always|byMeshName, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureMethod?: normalMap|mesh, positionMode?: boundingBox|boundingSphere|none, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, lowSuffix?, highSuffix?}", + "{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), model?: complete nested BakeSettings (named enum values), preserveEnabled?: keep each texture set enabled flag when replacing the model, patch?: nested BakeSettings fields to update after model (omitted fields stay unchanged, null clears optional fields), resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?: never|always|byMeshName, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureMethod?: normalMap|mesh, positionMode?: boundingBox|boundingSphere|none, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, lowSuffix?, highSuffix?}", always, settings ), @@ -90,6 +92,10 @@ fn parse_mesh(file_name: &str, bytes: Vec) -> Result { impl Session { pub fn bake_task(&self, ts: usize) -> Result { let set = self.doc.project.texture_set(ts)?; + if !set.has_enabled_bake_tiles() { + return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name))); + } + let needs_low_color = set.bake.maps.opacity.is_enabled || (set.bake.maps.id.is_enabled && set.bake.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor); let low_base_color = if needs_low_color && (set.bake.high_poly.use_low_as_high || self.bake_meshes.high.is_empty()) { @@ -112,14 +118,25 @@ impl Session { } else { None }; - let skew = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Skew)).cloned()); - let cage_paint = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Cage)).cloned()); - let tiles = set.tile_grid().map_or((1, 1), |g| (g.cols, g.rows)); + let painted = |target| high.as_ref().and(self.doc.bake_paint.get(&(ts, target))).map(|map| super::layout::paint_for_bake(map, set)).transpose(); + let skew = painted(BakePaintTarget::Skew)?; + let cage_paint = painted(BakePaintTarget::Cage)?; + let grid = set.tile_grid(); + let tiles = grid.map_or((1, 1), |grid| (grid.cols, grid.rows)); + let excluded_tiles: Vec<_> = set.uv_tiles.iter().filter(|tile| set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid?.block(*tile)).collect(); + let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&ts).cloned().unwrap_or_default() }; let tracer = GPU_TRACER.get().cloned(); Ok(BakeTask { low_base_color, ts, - mesh: self.mesh.clone(), + mesh: match grid.filter(|_| !set.tile_resolutions.is_empty()) { + Some(grid) => { + let mut mesh = (*self.source).clone(); + mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array()))); + Arc::new(mesh) + } + None => self.mesh.clone(), + }, bvh: self.bvh.clone(), material: set.material, settings: set.bake.clone(), @@ -128,6 +145,8 @@ impl Session { skew, cage_paint, tiles, + excluded_tiles, + previous_maps, tracer, }) } @@ -364,7 +383,7 @@ pub fn settings_params(settings: &BakeSettings) -> Value { /// Apply only the bake parameters supplied by the caller fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> Result<()> { - // Keep the current command limits until the reference controls are integrated + // Preserve the legacy flat-parameter limits for existing callers const MAX_DILATION_PIXELS: u32 = 256; const MAX_SUFFIX_CHARS: usize = 64; @@ -378,6 +397,14 @@ fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> } } + if let Some(patch) = params.get("patch") { + let mut model = json!(settings); + model_patch::apply_patch(&mut model, patch, command)?; + let updated: BakeSettings = serde_json::from_value(model).map_err(|error| bad(command, error.to_string()))?; + validate_model_settings(&updated, command)?; + *settings = updated; + } + if let Some(resolution) = u64p(params, "resolution") { settings.common.resolution = u32::try_from(resolution) .ok() @@ -604,8 +631,15 @@ fn settings(session: &mut Session, params: &Value) -> Result { } fn bake_run(session: &mut Session, params: &Value) -> Result { - let next = updated_settings(session, params, "bake.run")?; + let next: Vec<_> = updated_settings(session, params, "bake.run")? + .into_iter() + .filter(|(index, _)| session.doc.project.texture_sets.get(*index).is_some_and(|texture_set| texture_set.has_enabled_bake_tiles())) + .collect(); let sets: Vec = next.iter().map(|(index, _)| *index).collect(); + if sets.is_empty() { + return Ok(json!({"baked": [], "tracer": []})); + } + let cpu = boolp(params, "cpu") == Some(true); let tracers = session.edit("Bake mesh maps", |session| { let mut tracers = Vec::with_capacity(next.len()); diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 075943b3..213e1ff6 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -1,11 +1,31 @@ +//! Baking tasks, commands, settings helpers, and the mesh-map baking API + mod bake_mesh; mod bake_meshes; mod bake_task; +mod layout; mod merged_high; +mod mesh_map_command; +mod model_patch; +mod paint_command; +mod preserve_tiles; +mod tile_command; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; pub use merged_high::MergedHigh; +pub use mesh_map_command::{install_gpu_tracer, meshes_json, settings_params}; +pub use model_patch::settings_patch; +pub use texturecraft_bake::*; + +use crate::CommandSpec; type MaterialColors = std::sync::Arc>>>; + +pub(crate) fn specs() -> Vec { + let mut commands = mesh_map_command::specs(); + commands.extend(paint_command::specs()); + commands.extend(tile_command::specs()); + commands +} diff --git a/crates/engine/src/bake/model_patch.rs b/crates/engine/src/bake/model_patch.rs new file mode 100644 index 00000000..871d7dc8 --- /dev/null +++ b/crates/engine/src/bake/model_patch.rs @@ -0,0 +1,40 @@ +use serde_json::{Value, json}; +use texturecraft_core::BakeSettings; + +use crate::Result; +use crate::commands::bad; + +/// Only the changed fields, using the persisted model's names and enum values +pub fn settings_patch(before: &BakeSettings, after: &BakeSettings) -> Value { + changed_fields(&json!(before), &json!(after)).unwrap_or_else(|| json!({})) +} + +fn changed_fields(before: &Value, after: &Value) -> Option { + if before == after { + return None; + } + + if let (Some(before), Some(after)) = (before.as_object(), after.as_object()) { + let fields = after + .iter() + .filter_map(|(name, value)| changed_fields(before.get(name).unwrap_or(&Value::Null), value).map(|change| (name.clone(), change))) + .collect(); + Some(Value::Object(fields)) + } else { + Some(after.clone()) + } +} + +/// Merge known fields only; null is a value, so optional settings can be cleared +pub(super) fn apply_patch(model: &mut Value, patch: &Value, command: &str) -> Result<()> { + let fields = patch.as_object().ok_or_else(|| bad(command, "bake settings patch must be an object"))?; + for (name, value) in fields { + let target = model.get_mut(name).ok_or_else(|| bad(command, format!("unknown bake setting `{name}`")))?; + if target.is_object() { + apply_patch(target, value, command)?; + } else { + *target = value.clone(); + } + } + Ok(()) +} diff --git a/crates/engine/src/bake_paint_cmds.rs b/crates/engine/src/bake/paint_command.rs similarity index 97% rename from crates/engine/src/bake_paint_cmds.rs rename to crates/engine/src/bake/paint_command.rs index 80cf4852..1bbe2580 100644 --- a/crates/engine/src/bake_paint_cmds.rs +++ b/crates/engine/src/bake/paint_command.rs @@ -6,7 +6,7 @@ use texturecraft_bake::BakePaintMap; use texturecraft_core::BakePaintTarget; use texturecraft_geom::glam::Vec2; -pub fn specs() -> Vec { +pub(super) fn specs() -> Vec { vec![ cmd!("bake.skew.set", "Set Skew Correction", [], None, "{ts?, value?: 0..1 | path: grayscale image}", always, |session, parameters| set( session, @@ -65,7 +65,7 @@ fn set(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Re session.doc.bake_paint.insert((texture_set, target), Arc::new(map)); Ok(()) })?; - Ok(crate::bake_cmds::meshes_json(session)) + Ok(super::meshes_json(session)) } fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { @@ -76,7 +76,7 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Ok(()) })?; } - Ok(crate::bake_cmds::meshes_json(session)) + Ok(super::meshes_json(session)) } fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { @@ -123,7 +123,7 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> } Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string())) })?; - Ok(crate::bake_cmds::meshes_json(session)) + Ok(super::meshes_json(session)) } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/bake/preserve_tiles.rs b/crates/engine/src/bake/preserve_tiles.rs new file mode 100644 index 00000000..27c74ae8 --- /dev/null +++ b/crates/engine/src/bake/preserve_tiles.rs @@ -0,0 +1,54 @@ +use texturecraft_bake::BakeOutput; +use texturecraft_compose::BakedMaps; + +use crate::{EngineError, Result}; + +/// Retain excluded tiles from the worker's snapshot, resampling when output size changes +pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_tiles: &[(u32, u32)], grid: (u32, u32)) -> Result<()> { + if excluded_tiles.is_empty() { + return Ok(()); + } + + let size = (output.resolution, output.height); + let tile_width = size.0 / grid.0.max(1); + let tile_height = size.1 / grid.1.max(1); + for (map, pixels) in &mut output.maps { + let components = map.components(); + for &(column, row) in excluded_tiles { + for y in row * tile_height..(row + 1) * tile_height { + let first = (y as usize * size.0 as usize + column as usize * tile_width as usize) * components; + let last = first + tile_width as usize * components; + let row_pixels = pixels.get_mut(first..last).ok_or_else(|| EngineError::Other("excluded UV tile lies outside the baked pixels".into()))?; + for (offset, pixel) in row_pixels.chunks_exact_mut(components).enumerate() { + let value = previous.sample(*map, column * tile_width + offset as u32, y, size).unwrap_or_else(|| map.neutral()); + for (component, value) in pixel.iter_mut().zip(value) { + *component = value; + } + } + } + } + } + + // Keep unchecked map outputs too when a partial bake changes the atlas dimensions + for map in previous.maps.keys() { + if output.maps.contains_key(map) || (previous.resolution == size.0 && previous.height(*map) == size.1) { + continue; + } + + let components = map.components(); + let count = (size.0 as usize) + .checked_mul(size.1 as usize) + .and_then(|count| count.checked_mul(components)) + .ok_or_else(|| EngineError::Other("resized bake map exceeds the addressable size".into()))?; + let mut pixels = Vec::new(); + pixels.try_reserve_exact(count).map_err(|error| EngineError::Other(format!("cannot retain mesh map {}: {error}", map.id())))?; + for y in 0..size.1 { + for x in 0..size.0 { + let value = previous.sample(*map, x, y, size).unwrap_or_else(|| map.neutral()); + pixels.extend(value.into_iter().take(components)); + } + } + output.maps.insert(*map, pixels); + } + Ok(()) +} diff --git a/crates/engine/src/bake/tile_command.rs b/crates/engine/src/bake/tile_command.rs new file mode 100644 index 00000000..766a4b84 --- /dev/null +++ b/crates/engine/src/bake/tile_command.rs @@ -0,0 +1,42 @@ +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, always, bad, boolp, u64p}; +use crate::set_cmds::ts_param; +use crate::{Result, Session, cmd}; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "bake.tile.set", + "Include UV tile in bake", + [], + None, + "{ts?, tile: UDIM number, enabled: bool} → {ts, tile, enabled}; excluded tiles keep existing baked pixels", + always, + set_enabled + )] +} + +fn set_enabled(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "bake.tile.set"; + let texture_set = ts_param(session, params, COMMAND)?; + let tile = u64p(params, "tile").and_then(|tile| u32::try_from(tile).ok()).ok_or_else(|| bad(COMMAND, "`tile` must be a UDIM number"))?; + let enabled = boolp(params, "enabled").ok_or_else(|| bad(COMMAND, "`enabled` must be true or false"))?; + let settings = session.doc.project.texture_set(texture_set)?; + if !settings.uv_tiles.contains(&tile) { + return Err(bad(COMMAND, format!("texture set {} has no UV tile {tile}", settings.name))); + } + + let was_enabled = !settings.bake_excluded_tiles.contains(&tile); + if enabled != was_enabled { + session.edit("Include UV tile in bake", |session| { + let settings = session.doc.project.texture_set_mut(texture_set)?; + if enabled { + settings.bake_excluded_tiles.remove(&tile); + } else { + settings.bake_excluded_tiles.insert(tile); + } + Ok(()) + })?; + } + Ok(json!({"ts": texture_set, "tile": tile, "enabled": enabled})) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 94bb350c..9f0d126b 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -68,8 +68,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); - v.extend(crate::bake_cmds::specs()); - v.extend(crate::bake_paint_cmds::specs()); + v.extend(crate::bake::specs()); v.extend(crate::materialx_cmds::specs()); v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 228d37e1..347b7390 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -129,26 +129,34 @@ pub fn texture_sets(s: &Session) -> Value { json!((0..s.set_count()).map(|i| texture_set(s, i)).collect::>()) } -/// One texture set; UV-tiled sets list their tiles and where each sits in the texel atlas. -pub fn texture_set(s: &Session, i: usize) -> Value { - let Some(t) = s.doc.project.texture_sets.get(i) else { return Value::Null }; - let grid = t.tile_grid(); - let tiles: Vec = - t.uv_tiles.iter().filter_map(|u| grid?.block(*u).map(|(x, y)| json!({ "udim": u, "block": [x, y], "resolution": t.tile_resolution(*u) }))).collect(); +/// One texture set, including UV tile layout and bake selection +pub fn texture_set(session: &Session, index: usize) -> Value { + let Some(texture_set) = session.doc.project.texture_sets.get(index) else { return Value::Null }; + + let grid = texture_set.tile_grid(); + let tiles: Vec = texture_set + .uv_tiles + .iter() + .filter_map(|tile| { + grid?.block(*tile).map(|(x, y)| { + json!({"udim": tile, "block": [x, y], "resolution": texture_set.tile_resolution(*tile), "bakeEnabled": !texture_set.bake_excluded_tiles.contains(tile)}) + }) + }) + .collect(); json!({ - "index": i, - "name": t.name, - "resolution": t.resolution, - "size": t.size(), - "blockResolution": t.block_resolution(), - "uvTiles": t.uv_tiles, + "index": index, + "name": texture_set.name, + "resolution": texture_set.resolution, + "size": texture_set.size(), + "blockResolution": texture_set.block_resolution(), + "uvTiles": texture_set.uv_tiles, "tiles": tiles, - "channels": t.channels.iter().map(|(c, f)| json!({ "channel": c.id(), "format": f.label() })).collect::>(), - "layers": s.doc.project.walk(i).len(), - "parts": crate::set_cmds::parts(s, i), - "baked": crate::project_cmds::baked_json(s.doc.baked.get(&i)), - "visible": t.visible, - "active": i == s.ts(), + "channels": texture_set.channels.iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label() })).collect::>(), + "layers": session.doc.project.walk(index).len(), + "parts": crate::set_cmds::parts(session, index), + "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), + "visible": texture_set.visible, + "active": index == session.ts(), }) } @@ -161,7 +169,7 @@ pub fn session(s: &Session) -> Value { "path": s.path, "modified": s.modified, "textureSets": texture_sets(s), - "bakeMeshes": crate::bake_cmds::meshes_json(s), + "bakeMeshes": crate::bake::meshes_json(s), "activeTextureSet": ts, "selectedLayer": s.selected_layer().map(|l| l.0), "target": match s.target { StackTarget::Content => json!("content"), StackTarget::Mask => json!("mask"), StackTarget::Effect(e) => json!(e.0) }, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ca7cdeea..00fd151e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,10 +8,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -pub mod bake_cmds; -#[path = "bake/mod.rs"] -mod bake_data; -mod bake_paint_cmds; +pub mod bake; pub mod brush_preset_cmds; pub mod camera_cmds; pub mod commands; @@ -50,14 +47,13 @@ pub mod tool_cmds; pub mod uv_tile_cmds; pub mod view_cmds; -pub use bake_data::{BakeMesh, BakeMeshes, BakeTask}; +pub use bake::{BakeMesh, BakeMeshes, BakeTask}; pub use commands::{CommandSpec, command_specs, execute, find}; pub use path_tool::PathState; pub use project_cmds::sample_session; pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; pub use set_cmds::{ResizeOutput, ResizeTask}; -pub use texturecraft_bake as bake; pub use texturecraft_compose as compose; pub use texturecraft_core as core; pub use texturecraft_formats as formats; diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 2220df34..0fbe1f5b 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -59,7 +59,7 @@ fn set(s: &mut Session, p: &Value) -> Result { None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)), // An atlas texel reads the image of the tile its mesh UV falls in. Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| { - let uv = set.from_atlas(grid, [u, v]); + let uv = grid.from_atlas([u, v]); udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) }), }; diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 1dc33631..f6f1ef9c 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -165,6 +165,7 @@ pub fn filter(id: &str, size: usize) -> Option>> { gbuf: &gbuf, pixels: &pixels, baked: &baked, + block_scales: p.texture_set(0).map(|set| set.block_scales()).unwrap_or_default(), preview: None, images: &images, bounds: mesh.bounds(), diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index aeaa5550..36263560 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -728,6 +728,7 @@ impl Session { gbuf: &cache.gbuf, pixels: &self.doc.pixels, baked: self.doc.baked.get(&ts).unwrap_or(&empty), + block_scales: cache.composite.block_scales.clone(), preview, images: &self.images, bounds: self.mesh.bounds(), @@ -816,6 +817,7 @@ impl Session { gbuf: &cache.gbuf, pixels: &self.doc.pixels, baked: self.doc.baked.get(&ts).unwrap_or(&empty), + block_scales: cache.composite.block_scales.clone(), preview: None, images: &self.images, bounds: self.mesh.bounds(), diff --git a/crates/engine/src/uv_tile_cmds.rs b/crates/engine/src/uv_tile_cmds.rs index d4659943..cd8c3a76 100644 --- a/crates/engine/src/uv_tile_cmds.rs +++ b/crates/engine/src/uv_tile_cmds.rs @@ -39,61 +39,69 @@ pub fn specs() -> Vec { ] } -fn tile_resolution(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "textureSet.tile.resolution"; - let ts = ts_param(s, p, CMD)?; - let tile = u64p(p, "tile").and_then(|t| u32::try_from(t).ok()).ok_or_else(|| bad(CMD, "`tile` (a UDIM number) is required"))?; - let r = u64p(p, "resolution").ok_or_else(|| bad(CMD, "`resolution` is required"))?; - let r = check_resolution(u32::try_from(r).unwrap_or(0))?; - let set = s.doc.project.texture_set(ts)?; - if !set.uv_tiles.contains(&tile) { - return Err(bad(CMD, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", set.name, set.uv_tiles))); +fn tile_resolution(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "textureSet.tile.resolution"; + let texture_set_index = ts_param(session, params, COMMAND)?; + let tile = u64p(params, "tile").and_then(|tile| u32::try_from(tile).ok()).ok_or_else(|| bad(COMMAND, "`tile` (a UDIM number) is required"))?; + let resolution = u64p(params, "resolution").ok_or_else(|| bad(COMMAND, "`resolution` is required"))?; + let resolution = check_resolution(u32::try_from(resolution).unwrap_or(0))?; + let texture_set = session.doc.project.texture_set(texture_set_index)?; + if !texture_set.uv_tiles.contains(&tile) { + return Err(bad(COMMAND, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", texture_set.name, texture_set.uv_tiles))); } - if set.tile_resolution(tile) == r { - return Ok(json!({ "ts": ts, "tile": tile, "resolution": r, "size": set.size() })); + + let removes_override = resolution == texture_set.resolution && texture_set.tile_resolutions.contains_key(&tile); + if texture_set.tile_resolution(tile) == resolution && !removes_override { + return Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": texture_set.size() })); } - s.cancel_stroke(); - let size = s.edit("UV tile resolution", |s| { - let set = s.doc.project.texture_set_mut(ts)?; - let old = set.clone(); - if r == set.resolution { - set.tile_resolutions.remove(&tile); + + session.cancel_stroke(); + let size = session.edit("UV tile resolution", |session| { + let texture_set = session.doc.project.texture_set_mut(texture_set_index)?; + let previous = texture_set.clone(); + if resolution == texture_set.resolution { + texture_set.tile_resolutions.remove(&tile); } else { - set.tile_resolutions.insert(tile, r); + texture_set.tile_resolutions.insert(tile, resolution); + } + check_size(texture_set)?; + let size = texture_set.size(); + if previous.tile_resolution(tile) != resolution { + relayout(&mut session.doc, texture_set_index, &previous, &mut session.log)?; } - check_size(set)?; - let size = set.size(); - relayout(&mut s.doc, ts, &old, &mut s.log)?; Ok(size) })?; - Ok(json!({ "ts": ts, "tile": tile, "resolution": r, "size": size })) + Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": size })) } -fn uv_tiles(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "textureSet.uvTiles"; - let ts = ts_param(s, p, CMD)?; - let enabled = boolp(p, "enabled").ok_or_else(|| bad(CMD, "`enabled` (true or false) is required"))?; - let set = s.doc.project.texture_set(ts)?; +fn uv_tiles(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "textureSet.uvTiles"; + let texture_set_index = ts_param(session, params, COMMAND)?; + let enabled = boolp(params, "enabled").ok_or_else(|| bad(COMMAND, "`enabled` (true or false) is required"))?; + let texture_set = session.doc.project.texture_set(texture_set_index)?; let tiles = if enabled { - detect_uv_tiles(&s.source, set.material, Some(true), &mut Vec::new()).map_err(|e| bad(CMD, format!("texture set \"{}\": {e}", set.name)))? + detect_uv_tiles(&session.source, texture_set.material, Some(true), &mut Vec::new()) + .map_err(|error| bad(COMMAND, format!("texture set \"{}\": {error}", texture_set.name)))? } else { Vec::new() }; - if tiles == set.uv_tiles { - return Ok(json!({ "ts": ts, "uvTiles": tiles, "dropped": [] })); + if tiles == texture_set.uv_tiles { + return Ok(json!({ "ts": texture_set_index, "uvTiles": tiles, "dropped": [] })); } - // Leaving UV tile mode keeps tile 1001 (UV 0..1), the area a classic set paints. - let dropped: Vec = set.uv_tiles.iter().copied().filter(|t| !enabled && *t != 1001).collect(); - s.cancel_stroke(); - s.edit(if enabled { "Use UV tiles" } else { "Stop using UV tiles" }, |s| { - let set = s.doc.project.texture_set_mut(ts)?; - let old = set.clone(); - set.tile_resolutions.retain(|u, _| tiles.contains(u)); - set.uv_tiles = tiles.clone(); - check_size(set)?; - relayout(&mut s.doc, ts, &old, &mut s.log) + + // Leaving UV tile mode keeps tile 1001, the area a classic set paints + let dropped: Vec = texture_set.uv_tiles.iter().copied().filter(|tile| !enabled && *tile != 1001).collect(); + session.cancel_stroke(); + session.edit(if enabled { "Use UV tiles" } else { "Stop using UV tiles" }, |session| { + let texture_set = session.doc.project.texture_set_mut(texture_set_index)?; + let previous = texture_set.clone(); + texture_set.tile_resolutions.retain(|tile, _| tiles.contains(tile)); + texture_set.bake_excluded_tiles.retain(|tile| tiles.contains(tile)); + texture_set.uv_tiles = tiles.clone(); + check_size(texture_set)?; + relayout(&mut session.doc, texture_set_index, &previous, &mut session.log) })?; - Ok(json!({ "ts": ts, "uvTiles": tiles, "dropped": dropped })) + Ok(json!({ "ts": texture_set_index, "uvTiles": tiles, "dropped": dropped })) } /// Mesh UV → normalized atlas position of UV tile layout `set` (None where the layout holds @@ -119,23 +127,30 @@ fn from_layout(set: &TextureSet, a: [f32; 2]) -> Option<[f32; 2]> { (set.uv_tiles.contains(&udim) && local.0 <= scale && local.1 <= scale).then(|| set.from_atlas(&g, a)) } -/// Resample texture set `ts`'s painted images and baked maps from layout `old` into the set's -/// current layout (inside [`Session::edit`] after changing the set). Notes go to `log`. +/// Move painted images into the working layout and baked maps only when the tile grid changes pub(crate) fn relayout(doc: &mut Document, ts: usize, old: &TextureSet, log: &mut Vec) -> Result<()> { let new = doc.project.texture_set(ts)?.clone(); - let map = |a: [f32; 2]| from_layout(&new, a).and_then(|m| to_layout(old, m)); - let ((ow, oh), (nw, nh)) = (old.size(), new.size()); - let texel = |x: f32, y: f32| map([x / nw as f32, y / nh as f32]).map(|o| (o[0] * ow as f32, o[1] * oh as f32)); - let all = TileImage::new(nw, nh, 1); + let map = |uv: [f32; 2]| from_layout(&new, uv).and_then(|mesh_uv| to_layout(old, mesh_uv)); + let (old_size, new_size) = (old.size(), new.size()); + let texel = |x: f32, y: f32| map([x / new_size.0 as f32, y / new_size.1 as f32]).map(|uv| (uv[0] * old_size.0 as f32, uv[1] * old_size.1 as f32)); + let all = TileImage::new(new_size.0, new_size.1, 1); let tiles: Vec<(u32, u32)> = (0..all.tiles_y()).flat_map(|ty| (0..all.tiles_x()).map(move |tx| (tx, ty))).collect(); - // Blocks and tiles are multiples of 64 texels (resolutions are powers of two ≥ 128), so the - // map is affine (or None) over each destination tile. - crate::layer_ops::map_set_images(doc, ts, |img, empty| remap_image(img, (nw, nh), empty, &texel, &tiles, true)); + + // Atlas blocks align with the 64-texel storage tiles, making each mapping affine + crate::layer_ops::map_set_images(doc, ts, |image, empty| remap_image(image, new_size, empty, &texel, &tiles, true)); remap_bake_paint(doc, ts, old, &new, &map)?; - if let Some(baked) = doc.baked.get(&ts) { - match remap_baked(baked, old, &new, &map) { - Some(b) => { - doc.baked.insert(ts, b); + + if old.uv_tiles != new.uv_tiles + && let Some(baked) = doc.baked.get(&ts) + { + let mut old_bake = old.clone(); + let mut new_bake = new.clone(); + old_bake.tile_resolutions.clear(); + new_bake.tile_resolutions.clear(); + let bake_map = |uv| from_layout(&new_bake, uv).and_then(|mesh_uv| to_layout(&old_bake, mesh_uv)); + match remap_baked(baked, &old_bake, &new_bake, &bake_map) { + Some(baked) => { + doc.baked.insert(ts, baked); } None => { doc.baked.remove(&ts); @@ -326,6 +341,28 @@ mod tests { assert!(execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1001, "resolution": 100})).is_err()); } + #[test] + fn removing_a_tile_override_at_the_sets_current_resolution_restores_inheritance() { + let mut session = udim_session(); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + execute(&mut session, "textureSet.resolution", &json!({"resolution": 128})).unwrap(); + let before = session.doc.project.clone(); + let history_steps = session.history_labels().len(); + + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + + assert!(session.doc.project.texture_sets[0].tile_resolutions.is_empty()); + assert_eq!(session.history_labels().len(), history_steps + 1); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert!(reopened.doc.project.texture_sets[0].tile_resolutions.is_empty()); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); + session.redo().unwrap(); + execute(&mut session, "textureSet.resolution", &json!({"resolution": 256})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].tile_resolution(1002), 256); + assert_eq!(session.doc.project.texture_sets[0].bake, before.texture_sets[0].bake); + } + #[test] fn export_writes_each_tile_at_its_own_size() { let mut s = udim_session(); diff --git a/crates/engine/tests/bake_resolution.rs b/crates/engine/tests/bake_resolution.rs new file mode 100644 index 00000000..620de675 --- /dev/null +++ b/crates/engine/tests/bake_resolution.rs @@ -0,0 +1,130 @@ +use std::sync::Arc; + +use serde_json::json; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::{NO_TRI, UvGBuffer, primitives}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = Session::new_project("Bake detail", primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap(); + execute(&mut session, "bake.settings", &json!({"resolution": 128, "maps": ["position"], "dilation": 0, "patch": {"common": {"apply_diffusion": false}}})) + .unwrap(); + session +} + +#[test] +fn working_tile_resolution_preserves_bake_samples_and_pixels() { + let mut session = session(); + let original = session.bake_task(0).unwrap().run(&Progress::new()).unwrap(); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + let task = session.bake_task(0).unwrap(); + let output = task.run(&Progress::new()).unwrap(); + assert_eq!((output.resolution, output.height), (256, 128)); + + let gbuffer = UvGBuffer::new(&task.mesh, task.material, output.resolution, output.height); + let mut samples = [0usize; 2]; + for (index, triangle) in gbuffer.tri.iter().enumerate() { + if *triangle != NO_TRI { + samples[(index % 256) / 128] += 1; + } + } + assert_eq!(samples, [128 * 128; 2], "each tile receives the full Bake Output Size"); + assert_eq!(output.maps, original.maps); +} + +#[test] +fn changing_working_resolution_never_resamples_stored_bakes() { + let mut session = session(); + let output = session.bake_task(0).unwrap().run(&Progress::new()).unwrap(); + session.apply_bake(0, output).unwrap(); + let original = session.doc.baked[&0].clone(); + for resolution in [128, 512, 256] { + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": resolution})).unwrap(); + let current = &session.doc.baked[&0]; + assert!(Arc::ptr_eq(¤t.maps[&BakedMap::Position], &original.maps[&BakedMap::Position]), "working resize must retain the bake buffer"); + assert_eq!(current, &original); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.baked[&0], original); + } + session.undo().unwrap(); + assert_eq!(session.doc.baked[&0], original); + session.redo().unwrap(); + assert_eq!(session.doc.baked[&0], original); + + for resolution in [512, 128] { + execute(&mut session, "textureSet.resolution", &json!({"resolution": resolution})).unwrap(); + assert!(Arc::ptr_eq(&session.doc.baked[&0].maps[&BakedMap::Position], &original.maps[&BakedMap::Position])); + } +} + +#[test] +fn rectangular_bakes_and_excluded_vertical_tiles_ignore_working_resolution() { + let mut mesh = primitives::udim_plane(); + let second_plane = mesh.uvs.len() / 2; + for uv in mesh.uvs.iter_mut().skip(second_plane) { + uv.x -= 1.0; + uv.y -= 1.0; + } + let mut session = Session::new_project("Vertical bake", mesh, "builtin:udim_plane", None, 256).unwrap(); + execute( + &mut session, + "bake.settings", + &json!({"resolution": 64, "maps": ["position"], "dilation": 0, "patch": {"common": {"resolution_height": "R128", "apply_diffusion": false}}}), + ) + .unwrap(); + let original = session.bake_task(0).unwrap().run(&Progress::new()).unwrap(); + assert_eq!((original.resolution, original.height), (64, 256)); + let pixels = original.maps.clone(); + session.apply_bake(0, original).unwrap(); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1011, "resolution": 128})).unwrap(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1011, "enabled": false})).unwrap(); + let output = session.bake_task(0).unwrap().run(&Progress::new()).unwrap(); + assert_eq!(output.maps, pixels, "rebaked and excluded tiles both keep their full rectangular detail"); +} + +#[test] +fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() { + use texturecraft_engine::compose::{DisplayKind, tile_bytes}; + use texturecraft_engine::formats::export::{Dest, ExportOptions, ExportPreset, FileFormat, MapSpec, SourceRef}; + + let mut session = session(); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + let image = image::GrayImage::from_fn(128, 128, |x, y| image::Luma([(x + y) as u8])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + for tile in [1001, 1002] { + session.import_resource_bytes(&format!("ao.{tile}.png"), bytes.clone()).unwrap(); + } + execute(&mut session, "textureSet.meshMap.set", &json!({"map": "ambientOcclusion", "image": "ao.1001.png"})).unwrap(); + while session.update() {} + + let baked = &session.doc.baked[&0]; + let map = BakedMap::AmbientOcclusion; + assert!((baked.scalar(map, 248, 120, (256, 128)).unwrap() - 240.0 / 255.0).abs() < 0.001); + let composite = &session.caches[0].composite; + let display = tile_bytes(composite, baked, DisplayKind::Orm, 5, 1); + assert_eq!(display[((56 * 64 + 56) * 4) as usize], 240, "the viewport samples the far corner of the smaller working tile"); + + let options = ExportOptions::new(ExportPreset { + name: "Bake detail".into(), + maps: vec![MapSpec { + file: "ao.$udim".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![(Dest::L, SourceRef::Baked { map, component: 0 })], + }], + }); + let files = session.export_files(&[0], &options).unwrap(); + let file = files.iter().find(|file| file.name == "ao.1002.png").unwrap(); + let exported = image::load_from_memory(&file.bytes).unwrap().to_luma8(); + assert_eq!(exported.dimensions(), (128, 128)); + assert_eq!(exported.get_pixel(120, 120)[0], 240); + assert_eq!(exported.get_pixel(10, 10)[0], 20); + + let layer = session.doc.project.texture_sets[0].stack[0]; + execute(&mut session, "mask.add.black", &json!({"layer": layer.0})).unwrap(); + execute(&mut session, "effect.add.generator", &json!({"layer": layer.0, "generator": "ambientOcclusion"})).unwrap(); + let mask = session.mask_at(layer, &[(376, 120), (266, 10)]).unwrap(); + assert_eq!(mask, vec![1.0, 0.0], "generators sample the whole bake through the working layout"); +} diff --git a/crates/engine/tests/bake_settings.rs b/crates/engine/tests/bake_settings.rs new file mode 100644 index 00000000..b22c53d9 --- /dev/null +++ b/crates/engine/tests/bake_settings.rs @@ -0,0 +1,112 @@ +use serde_json::json; +use texturecraft_engine::core::{BakeResolution, BakeSettings}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = Session::new_project("Bake settings", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let second = &mut session.doc.project.texture_sets[1].bake; + second.common.is_enabled = false; + second.common.resolution = BakeResolution::R128; + second.common.resolution_height = Some(BakeResolution::R256); + second.maps.ao.is_enabled = false; + second.maps.ao.parameters.rays.min_distance = 0.25; + second.maps.ao.parameters.rays.rays = 16; + second.maps.height.parameters.scaling_divisor = 2.0; + session +} + +#[test] +fn nested_settings_patch_preserves_other_fields_and_is_one_undo_step() { + let mut session = session(); + let before = session.doc.project.clone(); + let history_steps = session.history_labels().len(); + let patch = json!({"maps": {"ao": {"parameters": {"rays": {"rays": 128}}}}}); + + let result = execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).unwrap(); + + let mut expected = before.clone(); + for texture_set in &mut expected.texture_sets { + texture_set.bake.maps.ao.parameters.rays.rays = 128; + } + assert_eq!(session.doc.project, expected); + assert_eq!(result.as_array().unwrap().len(), 2); + assert_eq!(result[1]["model"], json!(expected.texture_sets[1].bake)); + assert_eq!(session.history_labels().len(), history_steps + 1); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.texture_sets, expected.texture_sets); + + session.undo().unwrap(); + assert_eq!(session.doc.project, before); + session.redo().unwrap(); + assert_eq!(session.doc.project, expected); +} + +#[test] +fn settings_patch_validates_every_target_before_changing_any() { + let mut session = session(); + let before = session.doc.project.clone(); + let history = session.history_labels(); + + // This maximum is valid for the active set but below the second set's minimum + let patch = json!({"maps": {"ao": {"parameters": {"rays": {"max_distance": 0.1}}}}}); + let error = execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).unwrap_err(); + assert!(error.to_string().contains("minimum occluder distance"), "{error}"); + assert_eq!(session.doc.project, before); + assert_eq!(session.history_labels(), history); +} + +#[test] +fn settings_patch_rejects_unknown_fields_and_invalid_shapes() { + let mut session = session(); + let before = session.doc.project.clone(); + let history = session.history_labels(); + + for patch in [ + json!(null), + json!([]), + json!({"unknown": 1}), + json!({"common": null}), + json!({"common": {"resolution": "invalid"}}), + json!({"common": {"antialiasing": true}}), + json!({"maps": {"ao": {"parameters": {"rays": {"rays": 257}}}}}), + json!({"maps": {"ao": {"parameters": {"rays": {"rayz": 128}}}}}), + ] { + assert!(execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).is_err(), "{patch}"); + assert_eq!(session.doc.project, before); + assert_eq!(session.history_labels(), history); + } +} + +#[test] +fn settings_patch_can_clear_optional_height_and_keeps_target_selection() { + let mut session = session(); + let first = session.doc.project.texture_sets[0].bake.clone(); + let mut second = session.doc.project.texture_sets[1].bake.clone(); + let patch = json!({"common": {"resolution_height": null}}); + + execute(&mut session, "bake.settings", &json!({"ts": [1], "patch": patch})).unwrap(); + + second.common.resolution_height = None; + assert_eq!(session.doc.project.texture_sets[0].bake, first); + assert_eq!(session.doc.project.texture_sets[1].bake, second); + + let history_steps = session.history_labels().len(); + execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": {}})).unwrap(); + execute(&mut session, "bake.settings", &json!({"ts": 1, "patch": patch})).unwrap(); + assert_eq!(session.history_labels().len(), history_steps); +} + +#[test] +fn settings_patch_can_reset_one_section_without_replacing_other_settings() { + let mut session = session(); + let mut expected = session.doc.project.clone(); + let defaults = BakeSettings::default().maps.ao.parameters; + for texture_set in &mut expected.texture_sets { + texture_set.bake.maps.ao.parameters = defaults; + } + + execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": {"maps": {"ao": {"parameters": defaults}}}})).unwrap(); + + assert_eq!(session.doc.project, expected); +} diff --git a/crates/engine/tests/bake_tiles.rs b/crates/engine/tests/bake_tiles.rs new file mode 100644 index 00000000..3f000321 --- /dev/null +++ b/crates/engine/tests/bake_tiles.rs @@ -0,0 +1,172 @@ +use std::sync::Arc; + +use serde_json::{Value, json}; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::compose::BakedMaps; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = Session::new_project("Tile baking", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + execute(&mut session, "bake.settings", &json!({"resolution": 32, "maps": ["ambientOcclusion"], "rays": 2})).unwrap(); + session +} + +#[test] +fn tile_selection_is_inspectable_saved_and_undoable() { + let mut session = session(); + let before = session.doc.project.clone(); + let result = execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + assert_eq!(result, json!({"ts": 0, "tile": 1002, "enabled": false})); + let selected = session.doc.project.clone(); + let inspected = execute(&mut session, "textureSet.inspect", &Value::Null).unwrap(); + assert_eq!(inspected["tiles"][0]["bakeEnabled"], true); + assert_eq!(inspected["tiles"][1]["bakeEnabled"], false); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project, selected); + + let history = session.history_labels(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + assert_eq!(session.history_labels(), history); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); + session.redo().unwrap(); + assert_eq!(session.doc.project, selected); + + for params in [json!({}), json!({"tile": 1003, "enabled": false}), json!({"tile": u64::MAX, "enabled": false}), json!({"tile": 1001, "enabled": 1})] { + assert!(execute(&mut session, "bake.tile.set", ¶ms).is_err()); + assert_eq!(session.doc.project, selected); + assert_eq!(session.history_labels(), history); + } +} + +#[test] +fn partial_bake_preserves_unchecked_tiles_and_uses_the_workers_selection() { + let mut session = session(); + session.doc.baked.insert(0, BakedMaps { resolution: 64, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32]))].into() }); + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + let mut task = session.bake_task(0).unwrap(); + task.tracer = None; + + // Editing the checkboxes while a bake runs affects the next bake + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": true})).unwrap(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1001, "enabled": false})).unwrap(); + let before = session.doc.baked.clone(); + let output = task.run(&Progress::new()).unwrap(); + session.apply_bake(0, output).unwrap(); + + let pixels = &session.doc.baked[&0].maps[&BakedMap::AmbientOcclusion]; + for row in pixels.chunks_exact(64) { + assert!(row[..32].iter().all(|value| *value > 0.99)); + assert!(row[32..].iter().all(|value| *value == 0.25)); + } + session.undo().unwrap(); + assert_eq!(session.doc.baked, before); +} + +#[test] +fn partial_bake_resizes_retained_tiles_and_unchecked_map_outputs() { + let mut session = session(); + session.doc.baked.insert( + 0, + BakedMaps { + resolution: 64, + maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32])), (BakedMap::Normal, Arc::new(vec![0.4; 64 * 32 * 3]))].into(), + }, + ); + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + let result = execute(&mut session, "bake.run", &json!({"resolution": 64, "cpu": true})).unwrap(); + assert_eq!(result["baked"], json!([0])); + + let baked = &session.doc.baked[&0]; + assert_eq!((baked.resolution, baked.height(BakedMap::AmbientOcclusion)), (128, 64)); + for row in baked.maps[&BakedMap::AmbientOcclusion].chunks_exact(128) { + assert!(row[..64].iter().all(|value| *value > 0.99)); + assert!(row[64..].iter().all(|value| *value == 0.25)); + } + assert_eq!(baked.maps[&BakedMap::Normal].len(), 128 * 64 * 3); + assert!(baked.maps[&BakedMap::Normal].iter().all(|value| *value == 0.4)); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.baked, session.doc.baked); +} + +#[test] +fn tile_selection_preserves_the_correct_udim_row() { + let mut mesh = primitives::udim_plane(); + let second_plane = mesh.uvs.len() / 2; + for uv in mesh.uvs.iter_mut().skip(second_plane) { + uv.x -= 1.0; + uv.y -= 1.0; + } + let mut session = Session::new_project("Vertical UV tiles", mesh, "builtin:udim_plane", None, 128).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1011]); + session.doc.baked.insert(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 32 * 64]))].into() }); + execute(&mut session, "bake.tile.set", &json!({"tile": 1011, "enabled": false})).unwrap(); + execute(&mut session, "bake.run", &json!({"resolution": 32, "maps": ["ambientOcclusion"], "rays": 2, "cpu": true})).unwrap(); + + let pixels = &session.doc.baked[&0].maps[&BakedMap::AmbientOcclusion]; + assert!(pixels[..32 * 32].iter().all(|value| *value == 0.25)); + assert!(pixels[32 * 32..].iter().all(|value| *value > 0.99)); +} + +#[test] +fn excluded_tiles_without_previous_pixels_use_neutral_values() { + let mut session = session(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1001, "enabled": false})).unwrap(); + execute(&mut session, "bake.run", &json!({"maps": ["normal", "ambientOcclusion"], "cpu": true})).unwrap(); + let baked = &session.doc.baked[&0]; + for map in [BakedMap::Normal, BakedMap::AmbientOcclusion] { + for row in baked.maps[&map].chunks_exact(64 * map.components()) { + for pixel in row[..32 * map.components()].chunks_exact(map.components()) { + assert_eq!(pixel, &map.neutral()[..map.components()]); + } + } + } +} + +#[test] +fn no_selected_tiles_is_a_noop_and_old_projects_include_every_tile() { + let mut session = session(); + let serialized = serde_json::to_value(&session.doc.project).unwrap(); + assert!(serialized["texture_sets"][0].get("bake_excluded_tiles").is_none()); + let legacy: texturecraft_engine::core::Project = serde_json::from_value(serialized).unwrap(); + assert!(legacy.texture_sets[0].has_enabled_bake_tiles()); + + for tile in [1001, 1002] { + execute(&mut session, "bake.tile.set", &json!({"tile": tile, "enabled": false})).unwrap(); + } + let before = session.doc.project.clone(); + let history = session.history_labels(); + let result = execute(&mut session, "bake.run", &json!({"ts": "selected", "cpu": true})).unwrap(); + assert_eq!(result["baked"], json!([])); + assert_eq!(session.doc.project, before); + assert!(session.doc.baked.is_empty()); + assert_eq!(session.history_labels(), history); + assert!(session.bake_task(0).is_err()); + + execute(&mut session, "textureSet.uvTiles", &json!({"enabled": false})).unwrap(); + assert!(session.doc.project.texture_sets[0].bake_excluded_tiles.is_empty()); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); +} + +#[test] +#[ignore] +fn partial_bake_timing() { + let mut session = session(); + execute(&mut session, "bake.run", &json!({"resolution": 256, "rays": 64, "cpu": true})).unwrap(); + for enabled in [true, false] { + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": enabled})).unwrap(); + let mut task = session.bake_task(0).unwrap(); + task.tracer = None; + let mut times = Vec::new(); + for _ in 0..5 { + let started = std::time::Instant::now(); + task.run(&Progress::new()).unwrap(); + times.push(started.elapsed()); + } + times.sort(); + eprintln!("{} of 2 UV tiles, 256 square, AO 64 rays, CPU: median {:?}, runs {:?}", if enabled { 2 } else { 1 }, times[2], times); + } +} diff --git a/crates/engine/tests/udim.rs b/crates/engine/tests/udim.rs index bcfab00b..aff12622 100644 --- a/crates/engine/tests/udim.rs +++ b/crates/engine/tests/udim.rs @@ -48,20 +48,24 @@ fn paint_red_at(s: &mut Session, p: Vec3) { #[test] fn uv_tiles_are_detected_and_inspected() { - let mut s = session(); - let set = execute(&mut s, "textureSet.inspect", &Value::Null).unwrap(); + let mut session = session(); + let set = execute(&mut session, "textureSet.inspect", &Value::Null).unwrap(); assert_eq!(set["uvTiles"], json!([1001, 1002])); assert_eq!(set["size"], json!([2 * RES, RES])); - assert_eq!(set["tiles"], json!([{ "udim": 1001, "block": [0, 0], "resolution": RES }, { "udim": 1002, "block": [1, 0], "resolution": RES }])); - assert_eq!(s.caches[0].size, (2 * RES, RES)); - // Explicit modes: classic on the UDIM plane, one tile on a 0..1 mesh. - execute(&mut s, "project.new", &json!({"mesh": "udim_plane", "resolution": RES, "uvTiles": false})).unwrap(); - assert!(s.doc.project.texture_sets[0].uv_tiles.is_empty()); - execute(&mut s, "project.new", &json!({"mesh": "plane", "resolution": RES})).unwrap(); - assert!(s.doc.project.texture_sets[0].uv_tiles.is_empty(), "UVs in 0..1 stay classic"); - execute(&mut s, "project.new", &json!({"mesh": "plane", "resolution": RES, "uvTiles": true})).unwrap(); - assert_eq!(s.doc.project.texture_sets[0].uv_tiles, vec![1001]); - assert_eq!(s.caches[0].size, (RES, RES)); + assert_eq!( + set["tiles"], + json!([{ "udim": 1001, "block": [0, 0], "resolution": RES, "bakeEnabled": true }, { "udim": 1002, "block": [1, 0], "resolution": RES, "bakeEnabled": true }]) + ); + assert_eq!(session.caches[0].size, (2 * RES, RES)); + + // Explicit modes: classic on the UDIM plane, one tile on a 0..1 mesh + execute(&mut session, "project.new", &json!({"mesh": "udim_plane", "resolution": RES, "uvTiles": false})).unwrap(); + assert!(session.doc.project.texture_sets[0].uv_tiles.is_empty()); + execute(&mut session, "project.new", &json!({"mesh": "plane", "resolution": RES})).unwrap(); + assert!(session.doc.project.texture_sets[0].uv_tiles.is_empty(), "UVs in 0..1 stay classic"); + execute(&mut session, "project.new", &json!({"mesh": "plane", "resolution": RES, "uvTiles": true})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, vec![1001]); + assert_eq!(session.caches[0].size, (RES, RES)); } #[test] diff --git a/crates/formats/README.md b/crates/formats/README.md index 7b28004e..a52e80a5 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -145,6 +145,11 @@ pub fn load_project(path: &Path) -> Result; // native allocated 64×64 tile `tx`, `ty` (u32 LE) and the raw `u16` LE components (sparse, lossless). Baked maps: the same header with 0 tiles, then `width × height × components` f32 LE. +Project format version 2 stores baked maps in uniform UV tile blocks, independent of working +tile-resolution overrides. Older projects load their stored bake pixels as-is, without converting +the old layout; their appearance may change until rebaked. Painted layers and cage/skew correction +maps retain their working atlas layout. + Loading runs `Project::validate`, refuses a newer `format_version` (`FormatError::NewerVersion`), checks every tile against its texture set's resolution and component count, rejects repeated or out-of-range tiles and trailing data, drops pixels of layers that are in no stack, and caps the diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index f8fc1b97..24fc9833 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -596,7 +596,9 @@ impl Sampler<'_> { fn baked(&self, m: BakedMap, at: At) -> [f32; 3] { match at { - At::Texel(x, y) if self.set.baked.contains(&m) => self.baked.sample(m, x, y, (self.res, self.comp.height)).unwrap_or(m.neutral()), + At::Texel(x, y) if self.set.baked.contains(&m) => { + self.baked.sample_working(m, x, y, (self.res, self.comp.height), &self.scales).unwrap_or(m.neutral()) + } _ => m.neutral(), } } diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 045dd0da..115ed5e0 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -455,6 +455,8 @@ fn load(reader: R) -> Result { // Ignore other entries from newer minor revisions } + pf.project.format_version = FORMAT_VERSION; + if recovered { pf.warnings.push( "Warning: Some project settings or mesh maps could not be imported. TextureCraft recovered what it could, using defaults where needed.".into(), diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 0a3c5067..7f756554 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -82,6 +82,26 @@ fn round_trip_is_identical_and_deterministic() { assert_same(&builtin, &load_project_bytes(&save_project_bytes(&builtin).unwrap()).unwrap()); } +#[test] +fn legacy_bakes_load_as_is_without_layout_conversion() { + let mut sample = sample(); + sample.pf.project.format_version = 1; + sample.pf.pixels.layers.clear(); + let set = &mut sample.pf.project.texture_sets[0]; + set.resolution = 256; + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 128); + let pixels: Vec = (0..16).flat_map(|y| (0..32).map(move |x| (y * 32 + x) as f32)).collect(); + sample.pf.baked.insert(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(pixels))].into() }); + + let loaded = load_project_bytes(&save_project_bytes(&sample.pf).unwrap()).unwrap(); + assert_eq!(loaded.project.format_version, FORMAT_VERSION); + assert_eq!(loaded.baked, sample.pf.baked, "old bake pixels are accepted without preserving their former layout"); + assert_eq!(loaded.bake_paint, sample.pf.bake_paint, "correction paint remains in the working layout"); + let reopened = load_project_bytes(&save_project_bytes(&loaded).unwrap()).unwrap(); + assert_same(&loaded, &reopened); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn save_and_load_through_files() { diff --git a/crates/render/src/mesh_maps.rs b/crates/render/src/mesh_maps.rs index bf811478..4bfb13dc 100644 --- a/crates/render/src/mesh_maps.rs +++ b/crates/render/src/mesh_maps.rs @@ -1,27 +1,46 @@ //! Debug textures for the mesh-map view. use texturecraft_compose::BakedMaps; -use texturecraft_core::BakedMap; -use texturecraft_texel::linear_to_srgb; +use texturecraft_core::{BakedMap, BlockScales}; /// RGBA8 of baked map `m` resampled to `size × size` stretched over the map (mid gray where not /// baked). Scalar maps are shown as grayscale; ID maps as their colors. Values are display /// (sRGB) encoded. -pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32) -> Vec { +pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32, working_size: (u32, u32), scales: &BlockScales) -> Vec { let size = size.max(1); let mut out = vec![128u8; (size * size * 4) as usize]; let Some(b) = baked.filter(|b| b.maps.contains_key(&m)) else { return out }; + for y in 0..size { for x in 0..size { - let v = b.sample(m, x, y, (size, size)).unwrap_or([0.5; 3]); + let uv = [(x as f32 + 0.5) / size as f32, (y as f32 + 0.5) / size as f32]; + let v = scales.bake_uv(uv, working_size).and_then(|uv| b.sample_uv(m, uv)).unwrap_or([0.5; 3]); let i = ((y * size + x) * 4) as usize; for k in 0..3 { - // Data maps are shown as stored, i.e. treated as display values. + // Data maps are shown as stored out[i + k] = (v[k].clamp(0.0, 1.0) * 255.0 + 0.5) as u8; } out[i + 3] = 255; } } - let _ = linear_to_srgb; out } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use texturecraft_core::TextureSet; + + #[test] + fn mesh_map_preview_places_bake_detail_in_the_working_tile() { + let mut set = TextureSet::new("Tiles", 0, 256); + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 128); + let pixels = (0..128).flat_map(|y| (0..256).map(move |x| ((x % 128) + y) as f32 / 255.0)).collect(); + let baked = BakedMaps { resolution: 256, maps: [(BakedMap::AmbientOcclusion, Arc::new(pixels))].into() }; + let preview = mesh_map_rgba(Some(&baked), BakedMap::AmbientOcclusion, 512, set.size(), &set.block_scales()); + assert_eq!(preview[(240 * 512 + 376) * 4], 240); + assert_eq!(preview[(400 * 512 + 500) * 4], 128, "unused working block area stays neutral"); + } +} diff --git a/crates/ui-egui/src/bake_mode.rs b/crates/ui-egui/src/bake_mode.rs deleted file mode 100644 index a5ee88f4..00000000 --- a/crates/ui-egui/src/bake_mode.rs +++ /dev/null @@ -1,112 +0,0 @@ -//! Bake Mode presentation; persisted settings live in core and edits use engine commands - -mod bake_paint_brush; -mod breadcrumb; -mod common_settings; -pub use bake_paint_brush::BakePaintBrush; -mod controls; -mod map_settings; -mod mesh_map_bakers; - -use egui::{Ui, vec2}; -use serde_json::json; -use texturecraft_engine::core::{BakeSettings, BakedMap}; - -use crate::TextureCraftApp; -use crate::i18n::{tr, trf}; -use crate::state::Mode; -use crate::widgets::primary_button; - -pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { - egui::ScrollArea::vertical().id_salt("bake_texture_sets").auto_shrink([false; 2]).show(ui, |ui| { - for set_index in 0..app.session.set_count() { - let Some(texture_set) = app.session.doc.project.texture_sets.get(set_index) else { continue }; - - let name = texture_set.name.clone(); - let (width, height) = texture_set.bake.common.output_size(); - let mut is_enabled = texture_set.bake.common.is_enabled; - ui.push_id(set_index, |ui| { - ui.horizontal(|ui| { - if ui.checkbox(&mut is_enabled, "").on_hover_text(tr("Include in Bake")).changed() { - app.run("bake.settings", json!({ "ts": set_index, "enabled": is_enabled })); - } - if ui.selectable_label(set_index == app.session.ts(), format!("{name} ({width} × {height})")).clicked() { - app.run("textureSet.select", json!({ "ts": set_index })); - } - }); - }); - } - }); -} - -/// The Mesh Map Bakers panel: which maps bake and which one Mesh Map Settings shows -pub fn mesh_map_bakers_panel(app: &mut TextureCraftApp, ui: &mut Ui) { - edit_settings(app, ui, "mesh_map_bakers", mesh_map_bakers::show); -} - -/// The Mesh Map Settings panel: the breadcrumb, then the selected map's parameters -pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { - let Some(texture_set) = app.session.doc.project.texture_sets.get(app.session.ts()) else { return }; - - let selected = selected_map(app.ui.selected_baked_map, &texture_set.bake); - breadcrumb::show(app, ui, selected); - ui.separator(); - edit_settings(app, ui, "mesh_map_settings", |_, ui, settings| ui.push_id(selected, |ui| map_settings::show(ui, selected, &mut settings.maps)).inner); -} - -/// The Common Settings panel: output, high poly, cage and skew settings -pub fn common_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { - edit_settings(app, ui, "bake_common_settings", common_settings::show); -} - -/// The map whose settings show: the chosen one, else the first enabled map, else Normal -fn selected_map(selection: Option, settings: &BakeSettings) -> BakedMap { - selection.or_else(|| settings.maps.enabled().next()).unwrap_or(BakedMap::Normal) -} - -/// Draw `contents` over a copy of the active set's bake settings and run `bake.settings` on change -fn edit_settings(app: &mut TextureCraftApp, ui: &mut Ui, scroll_id: &str, contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings)) { - let set_index = app.session.ts(); - let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return }; - - let mut settings = before.clone(); - egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)); - if settings != before { - app.run("bake.settings", json!({ "ts": set_index, "model": settings })); - } -} - -pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { - egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show( - ctx, - |ui| { - ui.horizontal(|ui| { - if let Some(progress) = app.bake_progress() { - ui.add(egui::ProgressBar::new(progress).desired_width(220.0).show_percentage()); - if ui.button(tr("Cancel")).clicked() { - app.cancel_bake(); - } - } else { - let texture_sets: Vec = app - .session - .doc - .project - .texture_sets - .iter() - .enumerate() - .filter(|(_, texture_set)| texture_set.bake.common.is_enabled) - .map(|(index, _)| index) - .collect(); - let label = trf("Bake Selected Textures ({n})", &[("n", &texture_sets.len())]); - if ui.add_enabled(!texture_sets.is_empty(), primary_button(ui, &label)).clicked() { - app.start_bake(texture_sets); - } - } - - if ui.button(tr("Return to Painting Mode")).clicked() { - app.ui.mode = Mode::Painting; - } - }); - }, - ); -} diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index fe4819a0..02d712a0 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -4,13 +4,14 @@ use crate::i18n::tr; use crate::widgets::icon_button; use egui::Ui; use egui_phosphor::regular as icon; -use serde_json::json; +use serde_json::{Map, Value, json}; use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; /// The output and high-poly sections, then cage (needs a high poly) and skew (needs a distance cage) -pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) -> Option { + let mut reset = Map::new(); ui.push_id("common", |ui| { // Restore Defaults keeps whether the texture set is included in the bake let is_enabled = settings.common.is_enabled; @@ -31,6 +32,11 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe ui.checkbox(&mut settings.common.apply_diffusion, tr("Apply Diffusion")); }) { settings.common = CommonBakeSettings { is_enabled, ..CommonBakeSettings::default() }; + let mut defaults = json!(settings.common); + if let Some(fields) = defaults.as_object_mut() { + fields.remove("is_enabled"); + } + reset.insert("common".into(), defaults); } }); @@ -53,6 +59,7 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe } }) { settings.high_poly = Default::default(); + reset.insert("high_poly".into(), json!(settings.high_poly)); } }); @@ -78,6 +85,7 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe } }) { settings.cage = Default::default(); + reset.insert("cage".into(), json!(settings.cage)); } }); @@ -100,10 +108,13 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); }) { settings.skew = Default::default(); + reset.insert("skew".into(), json!(settings.skew)); } }); } } + + (!reset.is_empty()).then_some(Value::Object(reset)) } fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { diff --git a/crates/ui-egui/src/bake_mode/map_settings.rs b/crates/ui-egui/src/bake_mode/map_settings.rs index 0b5ac9e0..5168d341 100644 --- a/crates/ui-egui/src/bake_mode/map_settings.rs +++ b/crates/ui-egui/src/bake_mode/map_settings.rs @@ -1,6 +1,8 @@ use super::controls::{choice, hint, integer, number}; use crate::i18n::tr; use egui::Ui; +use serde::Serialize; +use serde_json::{Value, json}; use texturecraft_engine::core::{ AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakedMap, BentNormalSettings, CurvatureMethod, CurvatureSettings, HeightNormalization, HeightSettings, IdColorGenerator, IdColorSource, IdSettings, MeshMapSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, @@ -8,28 +10,33 @@ use texturecraft_engine::core::{ }; /// Draw `map`'s parameters with Restore Defaults; maps without parameters say so -pub(super) fn show(ui: &mut Ui, map: BakedMap, settings: &mut MeshMapSettings) { +pub(super) fn show(ui: &mut Ui, map: BakedMap, settings: &mut MeshMapSettings) -> Option { match map { - BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => hint(ui, tr("No Parameters")), - BakedMap::Id => parameters(ui, &mut settings.id.parameters, id), - BakedMap::AmbientOcclusion => parameters(ui, &mut settings.ao.parameters, ambient_occlusion), - BakedMap::Curvature => parameters(ui, &mut settings.curvature.parameters, curvature), - BakedMap::Position => parameters(ui, &mut settings.position.parameters, position), - BakedMap::Thickness => parameters(ui, &mut settings.thickness.parameters, thickness), - BakedMap::Height => parameters(ui, &mut settings.height.parameters, height), - BakedMap::BentNormal => parameters(ui, &mut settings.bent_normal.parameters, bent_normal), + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => { + hint(ui, tr("No Parameters")); + None + } + BakedMap::Id => parameters(ui, "id", &mut settings.id.parameters, id), + BakedMap::AmbientOcclusion => parameters(ui, "ao", &mut settings.ao.parameters, ambient_occlusion), + BakedMap::Curvature => parameters(ui, "curvature", &mut settings.curvature.parameters, curvature), + BakedMap::Position => parameters(ui, "position", &mut settings.position.parameters, position), + BakedMap::Thickness => parameters(ui, "thickness", &mut settings.thickness.parameters, thickness), + BakedMap::Height => parameters(ui, "height", &mut settings.height.parameters, height), + BakedMap::BentNormal => parameters(ui, "bent_normal", &mut settings.bent_normal.parameters, bent_normal), } } /// A map's controls, then a right-aligned Restore Defaults that resets only its parameters -fn parameters(ui: &mut Ui, parameters: &mut T, controls: impl FnOnce(&mut Ui, &mut T)) { +fn parameters(ui: &mut Ui, map_key: &str, parameters: &mut T, controls: impl FnOnce(&mut Ui, &mut T)) -> Option { controls(ui, parameters); ui.add_space(6.0); let restore = ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| ui.button(tr("Restore Defaults"))).inner; if restore.clicked() { *parameters = T::default(); + return Some(json!({"maps": {map_key: {"parameters": parameters}}})); } + None } fn id(ui: &mut Ui, settings: &mut IdSettings) { diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs new file mode 100644 index 00000000..3a308a4a --- /dev/null +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -0,0 +1,216 @@ +//! Bake Mode presentation; persisted settings live in core and edits use engine commands + +mod bake_paint_brush; +mod breadcrumb; +mod common_settings; +pub use bake_paint_brush::BakePaintBrush; +mod controls; +mod map_settings; +mod mesh_map_bakers; + +use egui::{Ui, vec2}; +use egui_phosphor::regular as icon; +use serde_json::{Value, json}; +use texturecraft_engine::bake::settings_patch; +use texturecraft_engine::core::{BakeSettings, BakedMap}; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::state::Mode; +use crate::widgets::{icon_button, primary_button}; + +pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { + egui::ScrollArea::vertical().id_salt("bake_texture_sets").auto_shrink([false; 2]).show(ui, |ui| { + for set_index in 0..app.session.set_count() { + let Some(texture_set) = app.session.doc.project.texture_sets.get(set_index) else { continue }; + + let name = texture_set.name.clone(); + let resolution = texture_set.resolution; + let mut is_enabled = texture_set.bake.common.is_enabled; + let visible = texture_set.visible; + let tiles: Vec<_> = texture_set + .uv_tiles + .iter() + .map(|tile| (*tile, texture_set.tile_resolutions.get(tile).copied(), !texture_set.bake_excluded_tiles.contains(tile))) + .collect(); + + ui.push_id(set_index, |ui| { + ui.horizontal(|ui| { + let button_size = ui.spacing().interact_size.y; + if icon_button(ui, if visible { icon::EYE } else { icon::EYE_SLASH }, tr("Show or hide the texture set"), false, button_size).clicked() { + app.run("textureSet.visible", json!({ "ts": set_index })); + } + if ui.checkbox(&mut is_enabled, "").on_hover_text(tr("Include in Bake")).changed() { + app.run("bake.settings", json!({ "ts": set_index, "enabled": is_enabled })); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if let Some(selected) = resolution_menu(ui, tr("Texture set resolution"), format!("{resolution} × {resolution}"), resolution, None) + && selected != resolution + { + app.start_resize(set_index, selected); + } + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if ui.add(egui::Button::selectable(set_index == app.session.ts(), &name).truncate()).on_hover_text(&name).clicked() { + app.run("textureSet.select", json!({ "ts": set_index })); + } + }); + }); + }); + + if !tiles.is_empty() { + egui::CollapsingHeader::new(format!("{} ({})", tr("UV tiles (UDIM)"), tiles.len())).default_open(true).show(ui, |ui| { + for (tile, override_resolution, enabled) in &tiles { + let mut enabled = *enabled; + ui.push_id(tile, |ui| { + ui.horizontal(|ui| { + if ui.checkbox(&mut enabled, tile.to_string()).on_hover_text(tr("Include in Bake")).changed() { + app.run("bake.tile.set", json!({"ts": set_index, "tile": tile, "enabled": enabled})); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let text = override_resolution.map(|value| format!("{value} × {value}*")).unwrap_or_default(); + let label = trf("UV tile {tile} resolution", &[("tile", &tile.to_string())]); + if let Some(selected) = resolution_menu( + ui, + &label, + text, + override_resolution.unwrap_or(resolution), + override_resolution.map(|_| resolution), + ) { + app.run("textureSet.tile.resolution", json!({"ts": set_index, "tile": tile, "resolution": selected})); + } + }); + }) + }); + } + }); + } + }); + } + }); +} + +fn resolution_menu(ui: &mut Ui, label: &str, text: String, resolution: u32, inherited_resolution: Option) -> Option { + let effective_size = format!("{resolution} × {resolution}"); + let measured = if text.is_empty() { &effective_size } else { &text }; + let font = egui::TextStyle::Button.resolve(ui.style()); + let text_width = ui.painter().layout_no_wrap(measured.clone(), font.clone(), ui.visuals().text_color()).size().x; + let width = text_width + ui.spacing().button_padding.x * 2.0; + let response = ui.add_sized([width, ui.spacing().interact_size.y], egui::Button::new("").frame(false)); + let popup_id = response.id.with("resolution_menu"); + let open = egui::Popup::is_id_open(ui.ctx(), popup_id) || response.clicked(); + let shown = if text.is_empty() && (response.hovered() || open) { effective_size } else { text }; + ui.painter().text(response.rect.center(), egui::Align2::CENTER_CENTER, &shown, font, ui.style().interact(&response).text_color()); + + let mut selected = None; + egui::Popup::menu(&response).id(popup_id).show(|ui| { + if let Some(inherited) = inherited_resolution { + if ui.button(tr("Remove resolution override")).clicked() { + selected = Some(inherited); + ui.close(); + } + ui.separator(); + } + for candidate in [128, 256, 512, 1024, 2048, 4096, 8192] { + if ui.selectable_label(candidate == resolution, format!("{candidate} × {candidate}")).clicked() { + selected = Some(candidate); + } + } + }); + response.widget_info(|| { + let mut info = egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), label); + info.current_text_value = Some(shown.clone()); + info + }); + response.on_hover_text(label); + selected +} + +/// The Mesh Map Bakers panel: which maps bake and which one Mesh Map Settings shows +pub fn mesh_map_bakers_panel(app: &mut TextureCraftApp, ui: &mut Ui) { + let texture_set = json!(app.session.ts()); + edit_settings(app, ui, "mesh_map_bakers", texture_set, |app, ui, settings| { + mesh_map_bakers::show(app, ui, settings); + None + }); +} + +/// The Mesh Map Settings panel: the breadcrumb, then the selected map's parameters +pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { + let Some(texture_set) = app.session.doc.project.texture_sets.get(app.session.ts()) else { return }; + + let selected = selected_map(app.ui.selected_baked_map, &texture_set.bake); + breadcrumb::show(app, ui, selected); + ui.separator(); + edit_settings(app, ui, "mesh_map_settings", json!("all"), |_, ui, settings| { + ui.push_id(selected, |ui| map_settings::show(ui, selected, &mut settings.maps)).inner + }); +} + +/// The Common Settings panel: output, high poly, cage and skew settings +pub fn common_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { + edit_settings(app, ui, "bake_common_settings", json!("all"), common_settings::show); +} + +/// The map whose settings show: the chosen one, else the first enabled map, else Normal +fn selected_map(selection: Option, settings: &BakeSettings) -> BakedMap { + selection.or_else(|| settings.maps.enabled().next()).unwrap_or(BakedMap::Normal) +} + +/// Send changed fields and explicitly reset sections through the same undoable command +fn edit_settings( + app: &mut TextureCraftApp, + ui: &mut Ui, + scroll_id: &str, + texture_sets: Value, + contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings) -> Option, +) { + let set_index = app.session.ts(); + let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return }; + + let mut settings = before.clone(); + let reset = egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)).inner; + if settings == before && reset.is_none() { + return; + } + + let mut patch = settings_patch(&before, &settings); + if let (Some(fields), Some(Value::Object(reset))) = (patch.as_object_mut(), reset) { + fields.extend(reset); + } + app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch })); +} + +pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { + egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show( + ctx, + |ui| { + ui.horizontal(|ui| { + if let Some(progress) = app.bake_progress() { + ui.add(egui::ProgressBar::new(progress).desired_width(220.0).show_percentage()); + if ui.button(tr("Cancel")).clicked() { + app.cancel_bake(); + } + } else { + let texture_sets: Vec = app + .session + .doc + .project + .texture_sets + .iter() + .enumerate() + .filter(|(_, texture_set)| texture_set.bake.common.is_enabled && texture_set.has_enabled_bake_tiles()) + .map(|(index, _)| index) + .collect(); + let label = trf("Bake Selected Textures ({n})", &[("n", &texture_sets.len())]); + if ui.add_enabled(!texture_sets.is_empty(), primary_button(ui, &label)).clicked() { + app.start_bake(texture_sets); + } + } + + if ui.button(tr("Return to Painting Mode")).clicked() { + app.ui.mode = Mode::Painting; + } + }); + }, + ); +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 77db5727..c6695b34 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -216,8 +216,14 @@ impl GpuLink { if self.aux.get(&ts) == Some(&key) { continue; } - let res = s.caches.get(ts).map_or(1024, |c| texturecraft_render::aux_size(c.size)); - out.aux.push((ts, res, texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res))); + let Some(cache) = s.caches.get(ts) else { continue }; + + let res = texturecraft_render::aux_size(cache.size); + out.aux.push(( + ts, + res, + texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res, cache.size, &cache.composite.block_scales), + )); self.aux.insert(ts, key); } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 294e8964..ebdc5ebc 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1055,4 +1055,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "الحد الأقصى للقيمة"), ("Value Bounds Min", "الحد الأدنى للقيمة"), ("Vertex Color", "لون الرأس"), + ("Remove resolution override", "إزالة تجاوز الدقة"), + ("Texture set resolution", "دقة مجموعة الخامات"), + ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 3155e6ce..c2b97532 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1104,4 +1104,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Maximaler Grenzwert"), ("Value Bounds Min", "Minimaler Grenzwert"), ("Vertex Color", "Scheitelpunktfarbe"), + ("Remove resolution override", "Auflösungsüberschreibung entfernen"), + ("Texture set resolution", "Auflösung des Textursets"), + ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 7ba164a9..5d29bf57 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1089,4 +1089,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Límite máximo"), ("Value Bounds Min", "Límite mínimo"), ("Vertex Color", "Color de vértice"), + ("Remove resolution override", "Quitar resolución personalizada"), + ("Texture set resolution", "Resolución del conjunto de texturas"), + ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 034d78b5..35f55392 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1113,4 +1113,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Borne maximale"), ("Value Bounds Min", "Borne minimale"), ("Vertex Color", "Couleur des sommets"), + ("Remove resolution override", "Supprimer la résolution personnalisée"), + ("Texture set resolution", "Résolution de l'ensemble de textures"), + ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 07ce31ea..b0df32cb 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1098,4 +1098,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite massimo"), ("Value Bounds Min", "Limite minimo"), ("Vertex Color", "Colore dei vertici"), + ("Remove resolution override", "Rimuovi risoluzione personalizzata"), + ("Texture set resolution", "Risoluzione del set di texture"), + ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index ac768443..eeb64614 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1083,4 +1083,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "値の上限"), ("Value Bounds Min", "値の下限"), ("Vertex Color", "頂点カラー"), + ("Remove resolution override", "解像度の上書きを解除"), + ("Texture set resolution", "テクスチャセットの解像度"), + ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 8fa260be..d8b13cfe 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1068,4 +1068,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "값 상한"), ("Value Bounds Min", "값 하한"), ("Vertex Color", "정점 색상"), + ("Remove resolution override", "해상도 재정의 제거"), + ("Texture set resolution", "텍스처 세트 해상도"), + ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 203a94de..444a903f 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1086,4 +1086,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite máximo"), ("Value Bounds Min", "Limite mínimo"), ("Vertex Color", "Cor do vértice"), + ("Remove resolution override", "Remover resolução personalizada"), + ("Texture set resolution", "Resolução do conjunto de texturas"), + ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index d651ba67..8bad2a36 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1014,4 +1014,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "值上限"), ("Value Bounds Min", "值下限"), ("Vertex Color", "顶点颜色"), + ("Remove resolution override", "移除分辨率覆盖"), + ("Texture set resolution", "纹理集分辨率"), + ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index df2d1c7a..acaf6385 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -128,7 +128,7 @@ impl TextureCraftApp { theme::install(&cc.egui_ctx); // Bakes cast their rays on a GPU device of their own (created on the first bake). #[cfg(not(target_arch = "wasm32"))] - texturecraft_engine::bake_cmds::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); + texturecraft_engine::bake::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx)); // The first run speaks the OS (or browser) language. let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_else(|| { diff --git a/crates/ui-egui/tests/bake_mode.rs b/crates/ui-egui/tests/bake_mode.rs index 7802f9d5..88a7c1f2 100644 --- a/crates/ui-egui/tests/bake_mode.rs +++ b/crates/ui-egui/tests/bake_mode.rs @@ -1,7 +1,7 @@ use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; -use texturecraft_engine::core::{BakeResolution, BakedMap, CageType, CurvatureMethod, HeightNormalization}; +use texturecraft_engine::core::{BakeResolution, BakeSettings, BakedMap, CageType, CurvatureMethod, HeightNormalization}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; use texturecraft_ui_egui::state::Mode; @@ -45,6 +45,306 @@ fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { harness.run_steps(3); } +fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { + let label_row = harness.get_by_label(label).rect().center().y; + harness.get_all_by_role(Role::TextInput).find(|node| (node.rect().center().y - label_row).abs() < 4.0).unwrap() +} + +#[test] +fn mesh_map_edits_update_all_sets_without_copying_unedited_fields() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + assert_eq!(session.set_count(), 2); + let second = &mut session.doc.project.texture_sets[1].bake; + *second = BakeSettings::default(); + second.common.is_enabled = false; + second.common.resolution = BakeResolution::R128; + second.common.resolution_height = Some(BakeResolution::R256); + second.maps.ao.is_enabled = false; + second.maps.ao.parameters.rays.rays = 16; + second.maps.ao.parameters.ground_plane.offset = 3.0; + second.maps.height.parameters.scaling_divisor = 2.0; + let before = session.doc.project.clone(); + let history_steps = session.history_labels().len(); + + click_checkbox(&mut harness, "Ground Plane"); + + let mut expected = before.clone(); + for texture_set in &mut expected.texture_sets { + texture_set.bake.maps.ao.parameters.ground_plane.enabled = true; + } + let session = &mut harness.state_mut().session; + assert_eq!(session.doc.project, expected); + assert_eq!(session.history_labels().len(), history_steps + 1); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); + session.redo().unwrap(); + assert_eq!(session.doc.project, expected); +} + +#[test] +fn common_settings_edits_update_all_sets_and_keep_their_map_selection() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + let second = &mut session.doc.project.texture_sets[1].bake; + *second = BakeSettings::default(); + second.common.is_enabled = false; + second.common.resolution = BakeResolution::R128; + second.maps.select([BakedMap::Height]); + let before = session.doc.project.clone(); + + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + click_checkbox(&mut harness, "Apply Diffusion"); + + let mut expected = before.clone(); + for texture_set in &mut expected.texture_sets { + texture_set.bake.common.apply_diffusion = false; + } + assert_eq!(harness.state().session.doc.project, expected); + + harness.get_all_by_value("64").next().unwrap().click(); + harness.run_steps(3); + click(&mut harness, "256"); + for texture_set in &mut expected.texture_sets { + texture_set.bake.common.resolution = BakeResolution::R256; + } + assert_eq!(harness.state().session.doc.project, expected); + + click_checkbox(&mut harness, "Use Low Poly Mesh as High Poly Mesh"); + for texture_set in &mut expected.texture_sets { + texture_set.bake.high_poly.use_low_as_high = true; + } + assert_eq!(harness.state().session.doc.project, expected); +} + +#[test] +fn secondary_rays_edit_from_another_set_updates_all_sets() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + session.doc.project.texture_sets[1].bake = BakeSettings::default(); + session.doc.project.texture_sets[1].bake.maps.ao.parameters.rays.rays = 16; + texturecraft_engine::execute(session, "textureSet.select", &serde_json::json!({"ts": 1})).unwrap(); + harness.run_steps(3); + select_map(&mut harness, "Ambient Occlusion"); + let history_steps = harness.state().session.history_labels().len(); + + number_field(&harness, "Secondary Rays").focus(); + harness.run_steps(2); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.run_steps(1); + number_field(&harness, "Secondary Rays").type_text("128"); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + let session = &harness.state().session; + assert_eq!(session.ts(), 1); + for texture_set in &session.doc.project.texture_sets { + assert_eq!(texture_set.bake.maps.ao.parameters.rays.rays, 128); + } + assert_eq!(session.history_labels().len(), history_steps + 1); +} + +#[test] +fn map_selection_stays_per_set() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let second = harness.state().session.doc.project.texture_sets[1].bake.clone(); + + click_checkbox(&mut harness, "Ambient Occlusion"); + assert!(enabled_maps(&harness).is_empty()); + assert_eq!(harness.state().session.doc.project.texture_sets[1].bake, second); + + click_checkbox(&mut harness, "Check All"); + assert_eq!(enabled_maps(&harness), BakedMap::ALL); + assert_eq!(harness.state().session.doc.project.texture_sets[1].bake, second); +} + +#[test] +fn bake_texture_set_visibility_is_independent_of_bake_selection() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let before: Vec<_> = harness.state().session.doc.project.texture_sets.iter().map(|texture_set| texture_set.bake.clone()).collect(); + let active_set = harness.state().session.ts(); + + harness.get_all_by_label("Show or hide the texture set").nth(1).unwrap().click(); + harness.run_steps(3); + + let session = &harness.state().session; + assert!(session.doc.project.texture_sets[0].visible); + assert!(!session.doc.project.texture_sets[1].visible); + assert_eq!(session.ts(), active_set); + for (texture_set, settings) in session.doc.project.texture_sets.iter().zip(&before) { + assert_eq!(&texture_set.bake, settings); + } + + harness.get_all_by_label("Show or hide the texture set").nth(1).unwrap().click(); + harness.run_steps(3); + assert!(harness.state().session.doc.project.texture_sets[1].visible); +} + +#[test] +fn texture_set_resolution_controls_are_independent_from_bake_output() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let before = harness.state().session.doc.project.clone(); + let active_set = harness.state().session.ts(); + harness.get_all_by_value("256 × 256").nth(1).unwrap().click(); + harness.run_steps(3); + click(&mut harness, "128 × 128"); + wait_for_resolution(&mut harness, 1, 128); + + let session = &harness.state().session; + assert_eq!(session.ts(), active_set); + assert_eq!(session.doc.project.texture_sets[0], before.texture_sets[0]); + assert_eq!(session.doc.project.texture_sets[1].bake, before.texture_sets[1].bake); + harness.state_mut().session.undo().unwrap(); + assert_eq!(harness.state().session.doc.project, before); +} + +fn wait_for_resolution(harness: &mut Harness<'_, TextureCraftApp>, texture_set: usize, resolution: u32) { + for _ in 0..100 { + harness.run_steps(1); + if harness.state().session.doc.project.texture_sets[texture_set].resolution == resolution { + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("texture set resize did not finish"); +} + +#[test] +fn tile_resolution_overrides_can_be_changed_and_removed_in_bake_mode() { + let session = texturecraft_engine::Session::new_project( + "Tile resolution controls", + texturecraft_engine::geom::primitives::udim_plane(), + "builtin:udim_plane", + None, + 256, + ) + .unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + let before = harness.state().session.doc.project.clone(); + + assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + let resolution_position = harness.get_by_label("UV tile 1002 resolution").rect().center(); + harness.hover_at(resolution_position); + harness.run_steps(3); + assert_eq!(harness.get_all_by_value("256 × 256").count(), 2); + harness.hover_at(egui::pos2(900.0, 500.0)); + harness.run_steps(3); + assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + harness.get_by_label("UV tile 1002 resolution").click(); + harness.run_steps(3); + click(&mut harness, "128 × 128"); + harness.get_by_value("128 × 128*"); + let texture_set = &harness.state().session.doc.project.texture_sets[0]; + assert_eq!(texture_set.resolution, 256); + assert_eq!(texture_set.tile_resolution(1001), 256); + assert_eq!(texture_set.tile_resolution(1002), 128); + assert_eq!(texture_set.bake, before.texture_sets[0].bake); + + harness.get_by_value("128 × 128*").click(); + harness.run_steps(3); + click(&mut harness, "Remove resolution override"); + assert_eq!(harness.state().session.doc.project, before); + assert!(harness.query_by_value("128 × 128*").is_none()); + assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + harness.state_mut().session.undo().unwrap(); + harness.run_steps(3); + harness.get_by_value("128 × 128*"); + + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_all_by_value("2048").next().unwrap().click(); + harness.run_steps(3); + click(&mut harness, "64"); + let texture_set = &harness.state().session.doc.project.texture_sets[0]; + assert_eq!(texture_set.resolution, 256); + assert_eq!(texture_set.tile_resolution(1002), 128); + assert_eq!(texture_set.bake.common.resolution, BakeResolution::R64); +} + +#[test] +fn bake_texture_sets_list_uv_tiles_and_their_resolutions() { + let mut session = + texturecraft_engine::Session::new_project("UV tile list", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256) + .unwrap(); + texturecraft_engine::execute(&mut session, "textureSet.tile.resolution", &serde_json::json!({"tile": 1002, "resolution": 128})).unwrap(); + let before = session.doc.project.clone(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + + harness.get_by_label("1001"); + harness.get_by_value("256 × 256"); + harness.get_by_label("1002"); + harness.get_by_value("128 × 128*"); + click_checkbox(&mut harness, "1002"); + assert!(harness.state().session.doc.project.texture_sets[0].bake_excluded_tiles.contains(&1002)); + assert!(!harness.get_by_label("Bake Selected Textures (1)").accesskit_node().is_disabled()); + click_checkbox(&mut harness, "1001"); + assert!(harness.get_by_label("Bake Selected Textures (0)").accesskit_node().is_disabled()); + harness.state_mut().session.undo().unwrap(); + harness.state_mut().session.undo().unwrap(); + harness.run_steps(3); + click(&mut harness, "UV tiles (UDIM) (2)"); + assert!(harness.query_by_label("1001").is_none()); + assert!(harness.query_by_label("1002").is_none()); + assert_eq!(harness.state().session.doc.project, before); +} + +#[test] +fn restoring_map_defaults_updates_other_sets_even_when_active_values_are_default() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + let second = &mut session.doc.project.texture_sets[1].bake; + *second = BakeSettings::default(); + second.common.is_enabled = false; + second.maps.ao.is_enabled = false; + second.maps.ao.parameters.rays.rays = 16; + second.maps.ao.parameters.ground_plane.offset = 3.0; + let before = session.doc.project.clone(); + + click(&mut harness, "Restore Defaults"); + + let mut expected = before.clone(); + expected.texture_sets[1].bake.maps.ao.parameters = BakeSettings::default().maps.ao.parameters; + let session = &mut harness.state_mut().session; + assert_eq!(session.doc.project, expected); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); +} + +#[test] +fn restoring_common_defaults_keeps_each_sets_inclusion_and_maps() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + session.doc.project.texture_sets[0].bake.common = Default::default(); + let second = &mut session.doc.project.texture_sets[1].bake; + *second = BakeSettings::default(); + second.common.is_enabled = false; + second.common.resolution = BakeResolution::R128; + second.common.resolution_height = Some(BakeResolution::R256); + second.common.apply_diffusion = false; + second.maps.select([BakedMap::Height]); + second.high_poly.low_suffix = "_custom_low".into(); + let before = session.doc.project.clone(); + + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_all_by_role_and_label(Role::Button, "Restore Defaults").next().unwrap().click(); + harness.run_steps(3); + + let mut expected = before.clone(); + expected.texture_sets[1].bake.common = Default::default(); + expected.texture_sets[1].bake.common.is_enabled = false; + let session = &mut harness.state_mut().session; + assert_eq!(session.doc.project, expected); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); +} + #[test] fn output_axes_unlock_independently_and_relock_to_width() { let mut harness = harness(None); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 31c4c35a..536d30d9 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -161,6 +161,51 @@ fn window_snapshots() { harness.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); } +#[test] +#[ignore] +fn bake_uv_tiles_snapshot() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { + eprintln!("set TC_UI_SNAPSHOTS= to write the pictures"); + return; + }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = + texturecraft_engine::Session::new_project("UV tile baking", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256) + .unwrap(); + texturecraft_engine::execute(&mut session, "textureSet.tile.resolution", &serde_json::json!({"tile": 1002, "resolution": 128})).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + save(&mut harness, &output_dir, "bake-uv-tiles"); + + harness.get_by_value("128 × 128*").click(); + save(&mut harness, &output_dir, "bake-tile-resolution-menu"); + harness.get_by_label("Remove resolution override").click(); + save(&mut harness, &output_dir, "bake-tile-resolution-inherited"); + assert!(harness.query_by_value("128 × 128*").is_none()); + assert!(harness.state().session.doc.project.texture_sets[0].tile_resolutions.is_empty()); + let inherited_resolution = harness.get_by_label("UV tile 1002 resolution").rect().center(); + harness.hover_at(inherited_resolution); + save(&mut harness, &output_dir, "bake-tile-resolution-hover"); + assert_eq!(harness.get_all_by_value("256 × 256").count(), 2); + harness.hover_at(egui::pos2(900.0, 500.0)); + harness.state_mut().session.undo().unwrap(); + harness.run_steps(3); + + harness.get_by_role_and_label(egui::Role::CheckBox, "1002").click(); + save(&mut harness, &output_dir, "bake-uv-tiles-partial"); + assert!(harness.state().session.doc.project.texture_sets[0].bake_excluded_tiles.contains(&1002)); + + harness.get_by_label("Show or hide the texture set").click(); + save(&mut harness, &output_dir, "bake-uv-tiles-hidden"); + assert!(!harness.state().session.doc.project.texture_sets[0].visible); + assert!(harness.state().session.doc.project.texture_sets[0].bake.common.is_enabled); +} + #[test] #[ignore] fn smart_mask_shelf_snapshot() { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 74322c74..78707aa1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -24,6 +24,39 @@ as the history reaches); `edit.history` lists the steps done and the undone ones Any command takes `merge: true` to fold its edit into the previous undo step when that step has the same label: a drag that applies a value on every frame stays one step. +Bake mode applies edits in Common Settings and Mesh Map Settings to every texture set. Each +set keeps its own enabled mesh-map checkboxes and Include in Bake flag. Edits update only the +changed fields; Restore Defaults resets the whole parameter section across all sets. + +`bake.settings {ts: "all", patch: {maps: {ao: {parameters: {rays: {rays: 128}}}}}}` changes +only AO secondary rays. A `patch` uses the nested `BakeSettings` field names and named enum +values returned in the command's `model` result; omitted fields retain each set's values, and +`null` clears optional fields such as `common.resolution_height`. All targeted sets are validated +before the edit is applied as one undo step. `model` still replaces the complete settings; +when combined, `patch` follows `model`, then the flat command parameters apply. Omitting `ts` +still targets the active set for scripts that need individual control. + +The bake texture-set list shows visibility eyes and expandable UV tile rows. Visibility affects +the viewport independently of bake inclusion. Its resolution menus edit the texture-set size +(`textureSet.resolution`) and individual tile overrides (`textureSet.tile.resolution`), independently +of Common Settings' bake Output Size. Overridden tiles display a resolution marked with an asterisk; +inherited tile resolutions appear only on hover or while their menu is open. Remove resolution +override hides the number and restores inheritance from the set, including when their current +sizes happen to match. + +Baked maps use a uniform UV tile atlas: every selected tile receives the full bake Output Size, +including rectangular output sizes. Changing a texture-set or tile working resolution preserves +the stored bake pixels. Materials, mesh-map previews, and exports sample those pixels through +the working tile layout. Older project files load their baked pixels as-is without layout +conversion; rebaking restores correct mapping and detail. + +`bake.tile.set {ts?, tile: 1002, enabled: false}` +excludes one UV tile; `textureSet.inspect` / `session.inspect` expose each tile's `bakeEnabled`. +Tile choices are saved and undoable. Unchecked tiles retain their previous baked pixels, resampled +if output size changes, or neutral values when no previous map exists. A running bake uses the +tile selection captured when its worker started. Sets with no checked tiles are skipped; their +geometry still contributes to occlusion when baking other tiles. + ## Control channel (desktop app) ```sh From 03a9870db20d77cf0f000567d629a3610969434c Mon Sep 17 00:00:00 2001 From: chasse20 Date: Fri, 6 Nov 2026 01:12:55 -0500 Subject: [PATCH 19/73] Fix shelf hover previews and clean up comments --- crates/engine/src/mask_preview.rs | 40 ++++++------ crates/engine/src/mask_preview_camera.rs | 19 +++--- crates/ui-egui/src/mask_preview_image.rs | 14 ++--- crates/ui-egui/src/mask_shape.rs | 10 +-- crates/ui-egui/src/preview_image.rs | 35 +++++------ crates/ui-egui/src/preview_request.rs | 10 +-- crates/ui-egui/src/preview_worker.rs | 35 +++++------ crates/ui-egui/src/shelf.rs | 43 +++++++------ crates/ui-egui/src/shelf_preview.rs | 29 ++++----- crates/ui-egui/src/thumbs.rs | 69 ++++++++++----------- crates/ui-egui/src/worker_preview.rs | 9 ++- crates/ui-egui/tests/shelf_hover_preview.rs | 62 +++++++++++++----- 12 files changed, 188 insertions(+), 187 deletions(-) diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs index 6e3f3525..a44757fc 100644 --- a/crates/engine/src/mask_preview.rs +++ b/crates/engine/src/mask_preview.rs @@ -1,6 +1,5 @@ -//! Smart mask shelf previews: the real smart masks on a baked preview shape. The shape -//! ([`primitives::preview_orb`]) is baked once; each preset is then applied with -//! `mask.smart.apply`, read back from the compositor and seen from a fixed camera. +//! Smart mask previews share one baked [`primitives::preview_orb`] +//! Presets use `mask.smart.apply` and the compositor, matching document masks use serde_json::json; use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; @@ -11,34 +10,33 @@ use crate::mask_preview_camera::MaskPreviewCamera; pub use crate::mask_preview_pixel::MaskPreviewPixel; use crate::{EngineError, Result, Session}; -/// Texture and bake size of the preview shape in texels (at 256 the edge lines break up). +/// Bake resolution in texels; 256 loses the thin edge lines const TEXTURE_PX: u32 = 512; -/// Camera rays per preview pixel along each axis (anti-aliased outline). +/// Camera rays per preview pixel along each axis (anti-aliased outline) const SUPERSAMPLE: usize = 2; -/// Bound camera samples and output allocations for shelf previews. +/// Bound camera samples and output allocations for shelf previews pub const MAX_PREVIEW_SIZE_PX: usize = 512; -/// AO and thickness rays per texel (the default is 64; fewer look the same at thumbnail size). +/// AO and thickness rays per texel; thumbnail detail needs fewer than the default const OCCLUSION_RAYS: u32 = 12; -/// Mesh curvature rays per texel (the default is 32; fewer look the same at thumbnail size). +/// Curvature rays per texel; thumbnail detail needs fewer than the default const CURVATURE_RAYS: u32 = 12; -/// Mesh curvature sampling radius relative to the bounding box: wide enough that edges read as -/// lines at thumbnail size, narrow enough that the round body does not count as an edge. +/// Radius relative to the bounding box; isolates panel edges from the round body const CURVATURE_RADIUS: f32 = 0.005; -/// The mesh maps the smart mask generators read. +/// The mesh maps the smart mask generators read const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; -/// Camera views kept at most (one per preview size: the shelf thumbnail and the hover preview). +/// Keep camera views for the thumbnail and hover preview sizes const CAMERAS_KEPT: usize = 2; -/// The baked preview shape and, per preview size, what its camera sees. +/// The baked preview shape and, per preview size, what its camera sees pub struct MaskPreview { session: Session, layer: LayerId, - /// Camera views of the most recently used preview sizes, oldest first (traced on first use). + /// Cached camera views, least recently used first cameras: Vec, } impl MaskPreview { - /// Bake the preview shape once (previews of any size reuse it). + /// Bake the preview shape once (previews of any size reuse it) pub fn new() -> Result { let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; let set = session.doc.project.texture_set_mut(0)?; @@ -58,15 +56,15 @@ impl MaskPreview { Ok(MaskPreview { session, layer, cameras: Vec::new() }) } - /// Smart mask `id` per preview pixel, row-major `size²`, None where the shape is not seen - /// Returns None for an unknown id or a size outside 1..=[`MAX_PREVIEW_SIZE_PX`]. + /// Row-major `size²` pixels, with None outside the shape + /// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] pub fn render(&mut self, id: &str, size: usize) -> Option>> { if !(1..=MAX_PREVIEW_SIZE_PX).contains(&size) { return None; } crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; - // Nothing is undone here; the snapshots would pile up over the presets + // Previews need no undo history; retaining snapshots grows memory across presets self.session.undo.clear(); let camera = camera_for(&mut self.cameras, &self.session, size)?; @@ -94,8 +92,7 @@ impl MaskPreview { } } -/// The camera view for `size²` previews of `session`'s shape, traced on first use (moved to the end -/// of `cameras`); past [`CAMERAS_KEPT`] the least recently used size goes. +/// Cache one camera per preview size, evicting the least recently used view fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a MaskPreviewCamera> { let rays_per_side = size * SUPERSAMPLE; let camera = match cameras.iter().position(|c| c.rays_per_side == rays_per_side) { @@ -114,7 +111,7 @@ fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, si mod tests { use super::*; - /// Mean absolute difference of the masks of two previews over the pixels both see. + /// Mean absolute difference of the masks of two previews over the pixels both see fn difference(a: &[Option], b: &[Option]) -> f32 { let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 @@ -154,7 +151,6 @@ mod tests { assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); assert!(preview.render("nope", size).is_none()); - // The same bake renders other sizes, showing the same mask let big = preview.render("edges_sharp", size * 3).unwrap(); let mean = |px: &[Option]| px.iter().flatten().map(|p| p.mask).sum::() / px.iter().flatten().count().max(1) as f32; assert_eq!(big.len(), size * size * 9); diff --git a/crates/engine/src/mask_preview_camera.rs b/crates/engine/src/mask_preview_camera.rs index 9787accb..ea3d6d1f 100644 --- a/crates/engine/src/mask_preview_camera.rs +++ b/crates/engine/src/mask_preview_camera.rs @@ -1,5 +1,4 @@ -//! The fixed camera of the smart mask previews (see [`crate::mask_preview::MaskPreview`]) at one -//! image size. +//! Cached camera rays for one smart mask preview size use std::collections::HashMap; @@ -8,27 +7,25 @@ use texturecraft_geom::surface_at; use crate::Session; -/// Camera: looking down by this angle, turned to show the front, left and top panels. +/// Camera angles expose the front, left and top panels const CAMERA_PITCH_DEG: f32 = 35.0; const CAMERA_YAW_DEG: f32 = -34.4; -/// What one camera ray sees: the index of its texel in [`MaskPreviewCamera::texels`] and the -/// view-space normal there (None where the ray misses). +/// Index into [`MaskPreviewCamera::texels`] and view-space normal; None on a miss pub(crate) type CameraSample = Option<(usize, Vec3)>; -/// What each ray of a square orthographic view of the preview shape sees. +/// What each ray of a square orthographic view of the preview shape sees pub(crate) struct MaskPreviewCamera { - /// Rays along each side of the view. + /// Rays along each side of the view pub rays_per_side: usize, - /// The texels (x, y) the camera sees, each once. + /// The texels (x, y) the camera sees, each once pub texels: Vec<(u32, u32)>, - /// Per ray, row-major `rays_per_side²`. + /// Per ray, row-major `rays_per_side²` pub samples: Vec, } impl MaskPreviewCamera { - /// Trace `rays_per_side²` rays at the shape of `session`, whose textures are `texture_px` - /// square. + /// Trace a square orthographic view onto a `texture_px²` texture pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> MaskPreviewCamera { let (lo, hi) = session.mesh.bounds(); let center = (lo + hi) * 0.5; diff --git a/crates/ui-egui/src/mask_preview_image.rs b/crates/ui-egui/src/mask_preview_image.rs index 49fe70f7..4418d099 100644 --- a/crates/ui-egui/src/mask_preview_image.rs +++ b/crates/ui-egui/src/mask_preview_image.rs @@ -1,28 +1,24 @@ -//! Shading of the smart mask previews: the mask as white over a near-black surface. +//! Smart masks appear white against a near-black surface use egui::{Color32, ColorImage}; use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::mask_preview::MaskPreviewPixel; use texturecraft_engine::texel::linear_to_srgb; -/// View-space directions of the key light (upper left) and a weaker fill (right), and how much -/// each lights the surface. +/// View-space lighting uses an upper-left key and a weaker right fill const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; const FILL: [f32; 3] = [0.7, -0.1, 0.7]; const AMBIENT: f32 = 0.1; const KEY_STRENGTH: f32 = 0.8; const FILL_STRENGTH: f32 = 0.35; -/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the -/// shape reads without looking glossy. +/// A faint sheen reveals the unmasked shape without a glossy finish const UNMASKED_ALBEDO: f32 = 0.006; const SHEEN: f32 = 0.1; const SHEEN_EXPONENT: f32 = 40.0; -/// Where the mask is full: white, darkened at most this much where unlit. +/// Where the mask is full: white, darkened at most this much where unlit const WHITE_SHADING: f32 = 0.2; -/// A smart mask preview (sRGB, transparent outside the shape) from preview pixels (row-major -/// `size²`): the mask as white over a near-black surface lit softly from the upper left. No -/// environment reflections. +/// Shade row-major `size²` mask pixels in sRGB with a transparent background pub fn mask_preview_image(size: usize, pixels: &[Option]) -> ColorImage { let key = Vec3::from(KEY).normalize(); let fill = Vec3::from(FILL).normalize(); diff --git a/crates/ui-egui/src/mask_shape.rs b/crates/ui-egui/src/mask_shape.rs index e34c5a7e..c99a9b1c 100644 --- a/crates/ui-egui/src/mask_shape.rs +++ b/crates/ui-egui/src/mask_shape.rs @@ -1,20 +1,20 @@ -//! The smart mask preview shape, baked on first use. +//! The smart mask preview shape, baked on first use use texturecraft_engine::mask_preview::MaskPreview; -/// Whether the smart mask preview shape is baked. +/// Whether the smart mask preview shape is baked #[derive(Default)] pub enum MaskShape { #[default] NotBaked, - /// Boxed: the baked session is large and the enum sits in the worker for its whole life. + /// Box the large session to keep the unbaked worker small Baked(Box), - /// The bake failed; smart mask previews stay empty. + /// The bake failed; smart mask previews stay empty Failed, } impl MaskShape { - /// The baked shape, baking it on the first call (about two seconds; None when it fails). + /// Bake on first use; retain failure to avoid retrying every frame pub fn get(&mut self) -> Option<&mut MaskPreview> { if matches!(self, MaskShape::NotBaked) { *self = match MaskPreview::new() { diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index 3f2321dc..f689c85d 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -1,5 +1,4 @@ -//! The CPU renderers of the shelf previews at any size: shaded material spheres, procedural -//! swatches, alpha swatches, brush strokes and letterboxed images (no image assets). +//! CPU renderers for shelf spheres, swatches, strokes and imported images use egui::{Color32, ColorImage}; use texturecraft_engine::compose::ImageRes; @@ -9,27 +8,25 @@ use texturecraft_engine::paint::{BrushSettings, Shape}; use texturecraft_engine::preview::{self, Sample}; use texturecraft_engine::texel::linear_to_srgb; -/// Pattern scale of the procedural swatches (repeats across the swatch). +/// Pattern scale of the procedural swatches (repeats across the swatch) const PROCEDURAL_SCALE: f32 = 3.0; -/// Samples per pixel along each axis of the alpha swatches. +/// Samples per pixel along each axis of the alpha swatches const ALPHA_SUPERSAMPLE: usize = 2; -/// Linear color of a surface with view-space normal `n` and these material values, lit by a key -/// light and a studio environment, seen along +Z. +/// Linear shading for view-space normal `n`, viewed along +Z pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { let l = [0.45f32, 0.7, 0.55]; let len = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt(); let l = l.map(|v| v / len); let ndl = (n[0] * l[0] + n[1] * l[1] + n[2] * l[2]).max(0.0); let ndv = n[2].max(0.0); - // View along +Z: half vector between light and view. + // The view direction is +Z let h = [l[0], l[1], l[2] + 1.0]; let hl = (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt(); let ndh = ((n[0] * h[0] + n[1] * h[1] + n[2] * h[2]) / hl).max(0.0); let shin = 2.0 / (rough * rough * rough * rough).max(1e-3) - 2.0; let spec_amt = ndh.powf(shin.clamp(1.0, 4096.0)) * (shin + 2.0) / 8.0; - // A studio environment seen in the mirror direction: dark floor, bright sky, a horizon that - // blurs (and the whole environment averages out) as roughness grows. + // Roughness blurs the reflected horizon toward the environment average let ry = 2.0 * ndv * n[1]; let w = 0.06 + rough * 0.9; let t = ((ry + w) / (2.0 * w)).clamp(0.0, 1.0); @@ -47,14 +44,13 @@ pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { out } -/// ACES filmic tone mapping of linear `x` (exposure folded in) to 0..=1. +/// ACES filmic tone mapping of linear `x` (exposure folded in) to 0..=1 pub fn aces(x: f32) -> f32 { let v = x * 0.6; ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) } -/// A shaded sphere image (sRGB, transparent outside) from per-pixel preview samples (row-major -/// `size²`, see [`preview::sphere_normals`]); height bumps the normals. +/// Shade row-major `size²` samples with height bumps and a transparent background pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); let r = (size as f32 * 0.5 - 1.0).max(0.5); @@ -64,9 +60,10 @@ pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { }; for (i, n) in preview::sphere_normals(size).enumerate() { let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; + let (x, y) = (i % size, i / size); let c = s.height; - // Central differences (image y points down). + // Image Y points down; the shading normal uses Y up let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); let k = r * 0.5 * 1.5; @@ -79,7 +76,7 @@ pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { img } -/// Grayscale `size²` swatch of procedural `kind`. +/// Grayscale `size²` swatch of procedural `kind` pub fn procedural_image(kind: ProceduralKind, size: usize) -> ColorImage { use texturecraft_engine::compose::pattern::{Coords, procedural}; use texturecraft_engine::core::{Procedural, Projection}; @@ -95,14 +92,13 @@ pub fn procedural_image(kind: ProceduralKind, size: usize) -> ColorImage { img } -/// White-on-black `size²` swatch of library alpha `alpha`. +/// White-on-black `size²` swatch of library alpha `alpha` pub fn alpha_image(alpha: &LibraryAlpha, size: usize) -> ColorImage { let pixels = alpha.render(size, ALPHA_SUPERSAMPLE).into_iter().map(|v| Color32::from_gray((v * 255.0 + 0.5) as u8)).collect(); ColorImage::new([size, size], pixels) } -/// Image resource `img` letterboxed into a `size²` square to keep its proportions, over black -/// where it is transparent. +/// Letterbox into a `size²` square, compositing transparency over black pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { let aspect = img.width as f32 / img.height.max(1) as f32; let (scale_u, scale_v) = if aspect >= 1.0 { (1.0, aspect) } else { (1.0 / aspect.max(1e-6), 1.0) }; @@ -124,15 +120,14 @@ pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { preview } -/// `b`'s stamps (shape, spacing, flow, angle, path following, jitters) along an S curve across -/// an `n`-pixel square, white on black. +/// Preview the brush along an S curve in an `n`-pixel square pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); let radius = n as f32 * 0.11; let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); let mut cover = vec![0f32; n * n]; - // Deterministic jitter per stamp. + // Stable jitter keeps the preview reproducible let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; let step = (b.spacing * 2.0 * radius).max(0.5); let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index 56e2e3b3..71c7870b 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -1,4 +1,4 @@ -//! A request to the shelf preview worker (see [`crate::preview_worker::PreviewWorker`]). +//! Shelf preview work submitted to [`crate::preview_worker::PreviewWorker`] use egui::ColorImage; @@ -6,20 +6,20 @@ use crate::mask_preview_image::mask_preview_image; use crate::mask_shape::MaskShape; use crate::shelf_preview::ShelfPreview; -/// Render `preview` at `size_px²`; the answer comes back under `key`. +/// Render `preview` at `size_px²`; the answer comes back under `key` pub struct PreviewRequest { pub key: String, pub preview: ShelfPreview, pub size_px: usize, - /// A hover preview: the worker renders the newest of these before anything else. + /// A hover preview: the worker renders the newest of these before anything else // The web renders each request at once, so nothing is reordered there #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub hover: bool, } impl PreviewRequest { - /// The requested image (None for an unknown asset, or a smart mask when the shape fails to - /// bake); smart masks bake `shape` on first use. + /// Render the asset, baking the mask shape on first use + /// Unknown assets and failed bakes return None pub fn render(&self, shape: &mut MaskShape) -> Option { match &self.preview { ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.render(id, self.size_px)?)), diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs index cf51812e..a3d2cc8f 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -1,35 +1,33 @@ -//! Renders shelf previews off the UI thread, on threads of its own (one core is left for the UI): -//! big hover previews and the smart mask thumbnails, which share one baked preview shape. On the web there are no threads: each request renders -//! inline on the UI thread (the window pauses for it). +//! Native preview rendering uses a separate thread pool +//! Web requests render synchronously on the UI thread #[cfg(target_arch = "wasm32")] use crate::mask_shape::MaskShape; use crate::preview_request::PreviewRequest; -/// A rendered preview: the request's key and its image (None when it could not be rendered). +/// Request key and rendered image; None on failure pub type PreviewResult = (String, Option); -/// The preview worker, started by the first request. +/// The preview worker, started by the first request #[derive(Default)] pub enum PreviewWorker { #[default] NotStarted, - /// The worker thread: requests go in, results come out (it ends when the requests sender is - /// dropped). + /// Native worker; dropping the request sender ends it after pending work #[cfg(not(target_arch = "wasm32"))] Running { requests: std::sync::mpsc::Sender, results: std::sync::mpsc::Receiver }, - /// The web: requests render as they are made. + /// The web: requests render as they are made #[cfg(target_arch = "wasm32")] Inline { shape: MaskShape, results: Vec }, - /// The worker could not start or stopped; requests are refused. + /// The worker could not start or stopped; requests are refused // The web has no thread to stop #[cfg_attr(target_arch = "wasm32", allow(dead_code))] Stopped, } impl PreviewWorker { - /// Queue `request`, starting the worker first if needed; false when the worker is stopped. - /// The worker repaints `ctx` when a result is ready. + /// Submit work, starting the worker on first use; false if it has stopped + /// Native results request a repaint pub fn request(&mut self, ctx: &egui::Context, request: PreviewRequest) -> bool { if matches!(self, PreviewWorker::NotStarted) { *self = PreviewWorker::start(ctx); @@ -53,7 +51,7 @@ impl PreviewWorker { } } - /// The results ready since the last call. + /// The results ready since the last call pub fn poll(&mut self) -> Vec { match self { #[cfg(not(target_arch = "wasm32"))] @@ -80,12 +78,12 @@ impl PreviewWorker { } } - /// Whether the worker stopped: it refuses requests and answers none of the queued ones. + /// Whether the worker stopped: it refuses requests and answers none of the queued ones pub fn is_stopped(&self) -> bool { matches!(self, PreviewWorker::Stopped) } - /// Start the worker thread (Stopped when it cannot start). + /// Start the worker thread (Stopped when it cannot start) #[cfg(not(target_arch = "wasm32"))] fn start(ctx: &egui::Context) -> PreviewWorker { use std::collections::VecDeque; @@ -97,7 +95,7 @@ impl PreviewWorker { let (result_tx, results) = channel(); let ctx = ctx.clone(); let spawned = std::thread::Builder::new().name("texturecraft-shelf-previews".into()).spawn(move || { - // Its own threads: on the global pool a big render would hold up the UI thread's work + // A separate pool keeps previews from queuing ahead of the UI's work let threads = std::thread::available_parallelism().map_or(1, |n| n.get().saturating_sub(1).max(1)); let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("texturecraft-preview-{i}")).build(); if let Err(e) = &pool { @@ -106,7 +104,6 @@ impl PreviewWorker { let mut shape = MaskShape::default(); let mut queue = VecDeque::new(); loop { - // Wait for work, then take in everything sent meanwhile if queue.is_empty() { let Ok(request) = request_rx.recv() else { break }; @@ -115,6 +112,7 @@ impl PreviewWorker { queue.extend(request_rx.try_iter()); let Some(request) = next_request(&mut queue) else { continue }; + let image = match &pool { Ok(pool) => pool.install(|| request.render(&mut shape)), Err(_) => request.render(&mut shape), @@ -135,15 +133,14 @@ impl PreviewWorker { } } - /// Render inline (no threads on the web). + /// Render inline (no threads on the web) #[cfg(target_arch = "wasm32")] fn start(_ctx: &egui::Context) -> PreviewWorker { PreviewWorker::Inline { shape: MaskShape::default(), results: Vec::new() } } } -/// The request to render next: the newest hover preview (the one under the pointer), else the -/// oldest request. +/// Prioritize the newest hover preview over older requests #[cfg(not(target_arch = "wasm32"))] fn next_request(queue: &mut std::collections::VecDeque) -> Option { match queue.iter().rposition(|request| request.hover) { diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 2617a56d..46ced908 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -26,25 +26,24 @@ use crate::theme::Tokens; use crate::thumbs::Thumbs; use crate::widgets::{dnd_release, icon_button}; -/// A shelf tile's size in points. +/// A shelf tile's size in points const TILE_WIDTH: f32 = 72.0; const TILE_HEIGHT: f32 = 86.0; -/// Corner radius of a tile's hover and selection highlights, in points. +/// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; -/// The thumbnail's size in a tile and its center below the tile's top, in points. +/// The thumbnail's size in a tile and its center below the tile's top, in points const THUMBNAIL_SIZE: f32 = 56.0; const THUMBNAIL_CENTER_Y: f32 = 32.0; -/// A placeholder disc's radius relative to the thumbnail's width. +/// A placeholder disc's radius relative to the thumbnail's width const PLACEHOLDER_RADIUS: f32 = 0.45; -/// A tile label's font size, its gap below the thumbnail and its total side margin, in points. +/// A tile label's font size, its gap below the thumbnail and its total side margin, in points const LABEL_FONT_SIZE: f32 = 9.5; const LABEL_GAP: f32 = 3.0; const LABEL_MARGIN: f32 = 4.0; -/// The hover preview's size and its gap above the label, in points. +/// The hover preview's size and its gap above the label, in points const BIG_PREVIEW_SIZE: f32 = 256.0; const BIG_PREVIEW_LABEL_GAP: f32 = 4.0; -/// How long the pointer rests on a tile before its big preview renders, in seconds (well inside -/// the popup's delay). +/// Dwell in seconds before rendering, shorter than the popup delay const BIG_PREVIEW_DWELL: f32 = 0.1; #[derive(Clone, Copy, PartialEq, Eq)] @@ -564,6 +563,7 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: tiles(ui, |ui| { for name in names { let Some(img) = app.session.images.get(&name).cloned() else { continue }; + let tex = app.thumbs.image(ctx, &name, &img); let asset = Asset::Texture(name.clone()); let preview = || ShelfPreview::Image(name.clone(), img); @@ -585,8 +585,7 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: }); } -/// A shelf tile: thumbnail (a placeholder disc while it renders) and a wrapped label; tiles with -/// a `drag` asset can be dragged. Hovering shows a big `preview` (made only then) over the label. +/// Asset tile with optional dragging and a larger hover preview fn tile( ui: &mut Ui, thumbs: &mut Thumbs, @@ -618,25 +617,26 @@ fn tile( resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) } -/// A hovered tile's big preview: requested once the pointer has rested [`BIG_PREVIEW_DWELL`], so -/// it renders during the popup's delay but not for tiles the pointer sweeps across (None until the -/// worker renders it). +/// Start rendering during the popup delay once the pointer rests fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPreview) -> Option { let ctx = ui.ctx(); - let size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; let preview = preview(); - // Keep smart mask hover previews within the camera's allocation limit at high display scales. - let size_px = if matches!(&preview, ShelfPreview::SmartMask(_)) { size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { size_px }; - let still_for = ui.input(|i| i.pointer.time_since_last_movement()); - if still_for >= BIG_PREVIEW_DWELL { + let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; + + // High display scales must respect the mask camera's allocation limit + let size_px = if matches!(&preview, ShelfPreview::SmartMask(_)) { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; + + // Scrolling moves tiles beneath a stationary pointer + let idle_seconds = ui.input(|input| if input.is_scrolling() { 0.0 } else { input.pointer.time_since_last_movement().min(input.time_since_last_scroll()) }); + if idle_seconds >= BIG_PREVIEW_DWELL { return thumbs.big(ctx, preview, size_px); } - ctx.request_repaint_after_secs(BIG_PREVIEW_DWELL - still_for); + ctx.request_repaint_after_secs(BIG_PREVIEW_DWELL - idle_seconds); thumbs.rendered_big(ctx, &preview, size_px) } -/// `tex` drawn into `rect`, or a placeholder disc while it renders. +/// `tex` drawn into `rect`, or a placeholder disc while it renders fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { match tex { Some(t) => { @@ -648,8 +648,7 @@ fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: e } } -/// A tile's hover popup: the `big` preview (the tile's `small` thumbnail scaled up until it -/// renders) over the label. +/// Use the thumbnail as a placeholder until the hover preview arrives fn hover_preview(ui: &mut Ui, small: Option<&egui::TextureHandle>, big: Option<&egui::TextureHandle>, label: &str) { let tk = Tokens::get(ui.ctx()); ui.set_max_width(BIG_PREVIEW_SIZE); diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index f8cc7e3b..a23ffb32 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -1,4 +1,4 @@ -//! What a shelf preview shows, and how to render it at any size. +//! Shelf assets and their preview renderers use std::sync::Arc; @@ -12,27 +12,26 @@ use texturecraft_engine::preview; use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_image, stroke_preview}; -/// The asset a shelf tile previews. +/// The asset a shelf tile previews pub enum ShelfPreview { - /// A built-in material or smart material on a sphere. + /// A built-in material or smart material on a sphere Material(&'static str), - /// A smart mask on the baked preview shape (only the preview worker can render it: see - /// [`crate::preview_request::PreviewRequest::render`]). + /// Smart mask rendering requires the worker's baked shape SmartMask(&'static str), - /// A library filter on a sample material on a sphere. + /// A library filter on a sample material on a sphere Filter(&'static str), - /// A procedural pattern as a grayscale swatch. + /// A procedural pattern as a grayscale swatch Procedural(ProceduralKind), - /// A library brush alpha, white on black. + /// A library brush alpha, white on black Alpha(&'static LibraryAlpha), - /// A brush preset's stroke along an S curve. + /// A brush preset's stroke along an S curve Brush(&'static BrushPreset), - /// An image resource by name. + /// An image resource by name Image(String, Arc), } impl ShelfPreview { - /// The cache key of the preview (one per asset). + /// The cache key of the preview (one per asset) pub fn key(&self) -> String { match self { ShelfPreview::Material(id) => format!("mat:{id}"), @@ -45,9 +44,8 @@ impl ShelfPreview { } } - /// The preview as a `size²` image (None for an unknown material or filter id). Smart masks are - /// None here: they need the baked preview shape, which only the preview worker holds, so the - /// UI thread never bakes. + /// Render a `size²` image; unknown assets return None + /// Smart masks return None here because their bake belongs to the worker pub fn image(&self, size: usize) -> Option { match self { ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), @@ -70,7 +68,7 @@ mod tests { use super::*; - /// The hover preview's size at 100 % scale. + /// The hover preview's size at 100 % scale const BIG_PX: usize = 256; #[test] @@ -91,7 +89,6 @@ mod tests { assert!(image.pixels.iter().any(|c| c.a() > 0 && c.r().max(c.g()).max(c.b()) > 0), "{key}: something shows"); } - // The shaded spheres come from finite material values let finite = |samples: Vec>| { samples.iter().flatten().all(|s| s.base.iter().chain([&s.metallic, &s.roughness, &s.height]).all(|v| v.is_finite())) }; diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 982caa17..9ed4f73b 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,7 +1,6 @@ -//! Thumbnails: shelf previews (see [`crate::preview_image`]) cached as egui textures, plus small -//! shaded spheres and alpha previews drawn as shapes. New shelf thumbnails are rendered lazily, a -//! few per frame, so opening the shelf never stalls a frame; the smart mask thumbnails and the big -//! hover previews render on a worker. +//! Shelf and brush preview caches +//! Small synchronous renders are limited per frame +//! Smart masks and hover previews use [`PreviewWorker`] use std::collections::{HashMap, VecDeque}; @@ -17,39 +16,39 @@ use crate::preview_worker::PreviewWorker; use crate::shelf_preview::ShelfPreview; use crate::worker_preview::WorkerPreview; -/// Shelf thumbnails rendered per frame at most (the rest follow on the next frames). +/// Shelf thumbnails rendered per frame at most (the rest follow on the next frames) const PER_FRAME: usize = 2; -/// Shelf sphere and smart mask thumbnail size in pixels. +/// Shelf sphere and smart mask thumbnail size in pixels const SPHERE_PX: usize = 72; -/// Shelf procedural swatch size in pixels. +/// Shelf procedural swatch size in pixels const PROCEDURAL_PX: usize = 56; -/// Shelf alpha and brush stroke swatch size in pixels. +/// Shelf alpha and brush stroke swatch size in pixels const SWATCH_PX: usize = 64; -/// Image resource preview size in pixels. +/// Image resource preview size in pixels const IMAGE_PX: usize = 64; -/// Big hover previews kept at most (the least recently shown go first). +/// Big hover previews kept at most (the least recently shown go first) const BIG_PREVIEWS_KEPT: usize = 32; -/// The shelf's and the brush panel's preview textures. +/// The shelf's and the brush panel's preview textures #[derive(Default)] pub struct Thumbs { - /// Shelf thumbnails by [`ShelfPreview::key`]. + /// Shelf thumbnails by [`ShelfPreview::key`] shelf: HashMap, images: HashMap, - /// (frame, thumbnails rendered in it). + /// (frame, thumbnails rendered in it) budget: (u64, usize), - /// Renders the smart mask thumbnails and the big previews. + /// Renders the smart mask thumbnails and the big previews worker: PreviewWorker, - /// Worker-rendered previews by [`worker_key`]. + /// Worker-rendered previews by [`worker_key`] rendered: HashMap, - /// The keys of the big previews in `rendered`, least recently shown first. + /// The keys of the big previews in `rendered`, least recently shown first big_shown: VecDeque, - /// The frame that last took in the worker's results. + /// The frame that last took in the worker's results received_in_pass: u64, } impl Thumbs { - /// A larger cached texture of an image resource for the stencil overlay (up to 1024 px). + /// A larger cached texture of an image resource for the stencil overlay (up to 1024 px) pub fn stencil(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { let key = format!("stencil:{name}"); if let Some(t) = self.images.get(&key) { @@ -70,7 +69,7 @@ impl Thumbs { t } - /// Cached preview of an image resource (64 px, letterboxed). + /// Cached preview of an image resource (64 px, letterboxed) pub fn image(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { if let Some(t) = self.images.get(name) { return t.clone(); @@ -80,8 +79,7 @@ impl Thumbs { t } - /// A cached shelf thumbnail of `preview` at `size_px²`, rendering it if this frame's budget - /// allows (None until then; a repaint is requested so it follows shortly). + /// Render within the frame budget; deferred thumbnails request a repaint fn shelf(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { let key = preview.key(); if let Some(t) = self.shelf.get(&key) { @@ -105,8 +103,8 @@ impl Thumbs { Some(t) } - /// A worker-rendered `size_px²` image of `preview`, requested on the first call (None until it - /// arrives, and for good when it cannot be rendered); `hover` previews jump the worker's queue. + /// Request once per asset and size; return None while pending or after failure + /// Hover requests take priority in the native worker fn worker_rendered(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize, hover: bool) -> Option { self.receive(ctx); @@ -118,7 +116,7 @@ impl Thumbs { self.ready(&key) } - /// The worker-rendered preview under `key` if it arrived. + /// The worker-rendered preview under `key` if it arrived fn ready(&self, key: &str) -> Option { match self.rendered.get(key) { Some(WorkerPreview::Ready(t)) => Some(t.clone()), @@ -126,8 +124,7 @@ impl Thumbs { } } - /// Take in the worker's finished previews, once per frame (dropping the ones no longer - /// wanted). + /// Poll once per pass and discard results evicted from the cache fn receive(&mut self, ctx: &egui::Context) { let pass = ctx.cumulative_pass_nr(); if self.received_in_pass == pass { @@ -152,8 +149,7 @@ impl Thumbs { } } - /// The big hover preview of `preview`, `size_px²` (None until the worker renders it; the - /// least recently shown are dropped past [`BIG_PREVIEWS_KEPT`]). + /// Request a hover preview and evict the least recently shown beyond the cache limit pub fn big(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { let key = worker_key(&preview, size_px); self.big_shown.retain(|k| *k != key); @@ -167,45 +163,44 @@ impl Thumbs { self.worker_rendered(ctx, preview, size_px, true) } - /// The big preview of `preview` if the worker already rendered it (requests nothing). + /// The big preview of `preview` if the worker already rendered it (requests nothing) pub fn rendered_big(&mut self, ctx: &egui::Context, preview: &ShelfPreview, size_px: usize) -> Option { self.receive(ctx); self.ready(&worker_key(preview, size_px)) } - /// Sphere thumbnail of built-in material `id`. + /// Sphere thumbnail of built-in material `id` pub fn material(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.shelf(ctx, ShelfPreview::Material(id), SPHERE_PX) } - /// Thumbnail of smart mask `id` on the baked preview shape (None while the worker renders - /// it). + /// Smart mask thumbnail; None until the worker returns it pub fn smart_mask(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false) } - /// Sphere thumbnail of library filter `id` applied to a sample material. + /// Sphere thumbnail of library filter `id` applied to a sample material pub fn filter(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.shelf(ctx, ShelfPreview::Filter(id), SPHERE_PX) } - /// Grayscale swatch of procedural `kind`. + /// Grayscale swatch of procedural `kind` pub fn procedural(&mut self, ctx: &egui::Context, kind: ProceduralKind) -> Option { self.shelf(ctx, ShelfPreview::Procedural(kind), PROCEDURAL_PX) } - /// White-on-black swatch of library alpha `alpha`. + /// White-on-black swatch of library alpha `alpha` pub fn alpha(&mut self, ctx: &egui::Context, alpha: &'static alphas::LibraryAlpha) -> Option { self.shelf(ctx, ShelfPreview::Alpha(alpha), SWATCH_PX) } - /// A brush preset's stroke along an S curve. + /// A brush preset's stroke along an S curve pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) } } -/// The key of a worker-rendered preview: one per asset and size. +/// The key of a worker-rendered preview: one per asset and size fn worker_key(preview: &ShelfPreview, size_px: usize) -> String { format!("{}@{size_px}", preview.key()) } diff --git a/crates/ui-egui/src/worker_preview.rs b/crates/ui-egui/src/worker_preview.rs index 0252d69f..53767276 100644 --- a/crates/ui-egui/src/worker_preview.rs +++ b/crates/ui-egui/src/worker_preview.rs @@ -1,13 +1,12 @@ -//! A preview rendered by the [`crate::preview_worker::PreviewWorker`], as the thumbnail cache -//! tracks it. +//! Cached state of a worker-rendered preview use egui::TextureHandle; -/// Where a worker-rendered preview is. +/// A pending, ready or failed preview pub enum WorkerPreview { - /// Requested; the worker has not answered yet. + /// Requested; the worker has not answered yet Rendering, Ready(TextureHandle), - /// The asset is unknown or the worker could not render it (the tile keeps its placeholder). + /// The asset is unknown or the worker could not render it (the tile keeps its placeholder) Failed, } diff --git a/crates/ui-egui/tests/shelf_hover_preview.rs b/crates/ui-egui/tests/shelf_hover_preview.rs index 1bb9a4d7..460ed7c8 100644 --- a/crates/ui-egui/tests/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/shelf_hover_preview.rs @@ -1,5 +1,4 @@ -//! Hovering a shelf tile shows a big preview of the asset over its name, rendered once the pointer -//! rests on the tile. +//! Shelf hover previews render after a dwell and appear above the asset name use std::time::{Duration, Instant}; @@ -9,20 +8,19 @@ use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::shelf_preview::ShelfPreview; -/// The shelf's Materials tab. +/// The shelf's Materials tab const MATERIALS_TAB: usize = 0; -/// The hover preview's size in points (pixels at this scale). +/// Popup image size in logical points, independent of display scale const BIG_PREVIEW_SIZE: f32 = 256.0; -/// Simulated seconds per frame, fine enough to stop between the rest and the popup's delay. +/// Small time steps distinguish preview scheduling from popup visibility const STEP_SECONDS: f32 = 0.001; -/// The popup's delay (egui's tooltip delay) and the rest after which the big preview renders. +/// Simulated delays in seconds for the popup and preview request const POPUP_DELAY: f32 = 0.5; const REST: f32 = 0.1; -/// Real time the worker gets to render. +/// Real time the worker gets to render const WORKER_TIMEOUT: Duration = Duration::from_secs(60); -/// The app on the Materials tab, `step_seconds` per frame, and two materials whose names show -/// nowhere else. +/// Open the Materials tab and find two labels unique to shelf tiles fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder() @@ -38,8 +36,7 @@ fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static (h, unique) } -/// The pixel size of the largest texture (not the font atlas) the last frame drew at least -/// `min_width` points wide. +/// Largest drawn texture in pixels, excluding fonts and images below `min_width` points fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_width: f32) -> Option<[usize; 2]> { let textures = h.ctx.tex_manager(); let textures = textures.read(); @@ -51,7 +48,7 @@ fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_width: f32) -> Op .max() } -/// Whether `material`'s big preview has arrived from the worker (asks for nothing). +/// Check the cache without submitting a preview request fn big_preview_ready(h: &mut Harness<'static, TextureCraftApp>, material: &SmartMaterial) -> bool { let ctx = h.ctx.clone(); h.state_mut().thumbs.rendered_big(&ctx, &ShelfPreview::Material(material.id), BIG_PREVIEW_SIZE as usize).is_some() @@ -65,7 +62,6 @@ fn hovering_a_shelf_tile_shows_its_big_preview() { assert!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE).is_none(), "nothing big before the hover"); h.get_by_label(material.label).hover(); - // The popup's delay, then the worker let big_px = BIG_PREVIEW_SIZE as usize; let start = Instant::now(); while largest_drawn_texture(&h, BIG_PREVIEW_SIZE) != Some([big_px, big_px]) && start.elapsed() < WORKER_TIMEOUT { @@ -74,7 +70,6 @@ fn hovering_a_shelf_tile_shows_its_big_preview() { } assert_eq!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE), Some([big_px, big_px]), "the popup draws the big preview"); - // The popup's name sits under the big image, below the tile let popup_name = h.get_all_by_label(material.label).map(|n| n.rect()).find(|r| r.min.y > tile.max.y).expect("the popup shows the name"); assert!(popup_name.min.y - tile.max.y >= BIG_PREVIEW_SIZE, "{popup_name:?} under {tile:?}"); } @@ -85,7 +80,7 @@ fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() { let (first, second) = (materials[0], materials[1]); let (from, to) = (h.get_by_label(first.label).rect().center(), h.get_by_label(second.label).rect().center()); - // A sweep: the pointer moves every frame across both tiles, then leaves the shelf + // Moving every frame must never satisfy the dwell delay let sweep_frames = 40; for frame in 0..=sweep_frames { h.hover_at(from.lerp(to, frame as f32 / sweep_frames as f32)); @@ -97,7 +92,7 @@ fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() { h.run_steps(1); assert!(!big_preview_ready(&mut h, first) && !big_preview_ready(&mut h, second), "a sweep renders nothing"); - // A rest: the preview renders before the popup opens + // A stationary pointer should start rendering before the popup opens h.hover_at(from); h.run_steps((REST * 1.2 / STEP_SECONDS) as usize); let start = Instant::now(); @@ -113,6 +108,41 @@ fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() { assert_eq!(h.query_all_by_label(first.label).count(), 1, "the popup is not open yet"); } +#[test] +fn scrolling_with_a_stationary_pointer_defers_the_big_preview() { + let (mut harness, materials) = materials_shelf(STEP_SECONDS, 1.0); + let material = materials[0]; + harness.get_by_label(material.label).hover(); + + // Scroll toward the top boundary to keep the same tile beneath the pointer + for _ in 0..(REST * 2.0 / STEP_SECONDS) as usize { + harness.input_mut().events.push(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, 10.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(1); + } + assert!(harness.ctx.input(|input| input.pointer.time_since_last_movement()) >= REST, "the pointer stayed still beyond the dwell delay"); + assert_eq!(harness.query_all_by_label(material.label).count(), 1, "scrolling suppresses the popup"); + + harness.hover_at(egui::pos2(900.0, 500.0)); + harness.run_steps(1); + std::thread::sleep(Duration::from_secs(1)); + harness.run_steps(1); + assert!(!big_preview_ready(&mut harness, material), "scrolling must not submit a hover preview"); + + harness.get_by_label(material.label).hover(); + let started = Instant::now(); + while !big_preview_ready(&mut harness, material) && started.elapsed() < WORKER_TIMEOUT { + harness.run_steps(1); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(big_preview_ready(&mut harness, material), "the preview renders after scrolling and pointer movement stop"); +} + #[test] fn high_dpi_smart_mask_hover_stays_within_the_renderer_limit() { use texturecraft_engine::mask_preview::MAX_PREVIEW_SIZE_PX; From f6b201010950c85301e6a8e7294e4d2bd0fc7595 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 06:46:26 +0000 Subject: [PATCH 20/73] Run every neighbourhood filter of a mask or content stack Only the last neighbourhood filter of a stack ran; any below it was skipped silently, so Blur then Warp gave the same result as Warp alone. field() now runs each one in turn, continuing from the previous field, over a region widened by what the filters above it read. Stacks with a single neighbourhood filter are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/eval.rs | 314 ++++++++++++++++++++++++------------- 1 file changed, 207 insertions(+), 107 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index ec75cd97..8b2d6be3 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -265,36 +265,35 @@ enum Op { Slope { scale: f32, seed: u32 }, } -/// Index (among visible effects) of the last neighbourhood filter of an effect stack, its -/// radius in texels (`res` texels per UV tile across) and what it does. +/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]). fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> { - let texels = |v: f32| (v * res as f32 / 2048.0).max(0.5); - effects - .iter() - .filter(|e| e.visible) - .enumerate() - .filter_map(|(i, e)| match &e.kind { - EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((i, texels(*radius), Op::Blur(None))), - EffectKind::Filter(Filter::Sharpen { amount }) => Some((i, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))), - EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((i, texels(*radius), Op::Line(direction(*angle)))), - EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => { - Some((i, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None })) - } - EffectKind::Filter(Filter::DirectionalWarp { intensity, angle, scale, seed }) if *intensity > 0.0 => { - Some((i, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: Some(direction(*angle)) })) - } - EffectKind::Filter(Filter::HighPass { radius }) => Some((i, texels(*radius), Op::HighPass)), - EffectKind::Filter(Filter::EdgeDetect { width }) => Some((i, texels(*width), Op::Edge)), - // Three box passes ramp an edge over about twice their radius. - EffectKind::Filter(Filter::Bevel { width }) => Some((i, texels(*width * 0.5), Op::Bevel)), - EffectKind::Filter(Filter::Glow { radius, amount }) => Some((i, texels(*radius), Op::Glow(*amount))), - EffectKind::Filter(Filter::Mosaic { size }) => Some((i, texels(*size), Op::Mosaic)), - EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => { - Some((i, texels(*radius), Op::Slope { scale: *scale, seed: *seed })) - } - _ => None, - }) - .last() + neighbourhood_filters(effects, res).last() +} + +/// The neighbourhood filters of an effect stack, bottom → top: index among the visible effects, radius in texels (`res` texels per UV tile across) and what it does. +fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator + '_ { + let texels = move |size: f32| (size * res as f32 / 2048.0).max(0.5); + effects.iter().filter(|effect| effect.visible).enumerate().filter_map(move |(index, effect)| match &effect.kind { + EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))), + EffectKind::Filter(Filter::Sharpen { amount }) => Some((index, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))), + EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((index, texels(*radius), Op::Line(direction(*angle)))), + EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => { + Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None })) + } + EffectKind::Filter(Filter::DirectionalWarp { intensity, angle, scale, seed }) if *intensity > 0.0 => { + Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: Some(direction(*angle)) })) + } + EffectKind::Filter(Filter::HighPass { radius }) => Some((index, texels(*radius), Op::HighPass)), + EffectKind::Filter(Filter::EdgeDetect { width }) => Some((index, texels(*width), Op::Edge)), + // Three box passes ramp an edge over about twice their radius + EffectKind::Filter(Filter::Bevel { width }) => Some((index, texels(*width * 0.5), Op::Bevel)), + EffectKind::Filter(Filter::Glow { radius, amount }) => Some((index, texels(*radius), Op::Glow(*amount))), + EffectKind::Filter(Filter::Mosaic { size }) => Some((index, texels(*size), Op::Mosaic)), + EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => { + Some((index, texels(*radius), Op::Slope { scale: *scale, seed: *seed })) + } + _ => None, + }) } /// Unit texel-space vector of `angle` degrees. Texel rows run down: positive angles turn @@ -528,153 +527,205 @@ enum Job<'a> { Content(Channel), } -/// One neighbourhood-filtered field of `layer` over `tiles` plus the filter's reach, built on -/// the fields already computed below it. +/// A layer's mask or content channel after every neighbourhood filter of its stack, over `tiles`. fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, tiles: &[(u32, u32)]) -> Option { - let (gw, gh) = (inp.gbuf.width, inp.gbuf.height); let effects = match job { - Job::Mask(m) => &m.effects, + Job::Mask(mask) => &mask.effects, Job::Content(_) => &inp.project.content_layer(id)?.content_effects, }; - let (k, radius, op) = neighbourhood(effects, inp.tile_res())?; - let opacity = effects.iter().filter(|e| e.visible).nth(k).map(|e| e.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); - // Clamped: a hostile radius must not overflow the halo and window arithmetic. - let r = radius.round().clamp(1.0, gw.max(gh) as f32) as u32; - // Three box passes reach 3r texels, the other filters r (and a texel for bilinear samples). - let blurs = matches!(op, Op::Blur(_) | Op::HighPass | Op::Bevel | Op::Glow(_)); - let reach = if blurs { 3 * r } else { r + 1 }; - let halo = reach.div_ceil(TILE); - let (tx0, ty0) = tiles.iter().fold((u32::MAX, u32::MAX), |(a, b), t| (a.min(t.0), b.min(t.1))); - let (tx1, ty1) = tiles.iter().fold((0, 0), |(a, b), t| (a.max(t.0), b.max(t.1))); - let (rx0, ry0) = (tx0.saturating_sub(halo) * TILE, ty0.saturating_sub(halo) * TILE); - let (rx1, ry1) = (((tx1 + 1 + halo) * TILE).min(gw), ((ty1 + 1 + halo) * TILE).min(gh)); - let (w, h) = (rx1.saturating_sub(rx0), ry1.saturating_sub(ry0)); - if w == 0 || h == 0 { - return None; + let filters: Vec<(usize, f32, Op)> = neighbourhood_filters(effects, inp.tile_res()).collect(); + let longest_side = inp.gbuf.width.max(inp.gbuf.height); + + // Each filter's region also holds what every filter above it reads around the tiles + let mut margins: Vec = filters.iter().map(|&(_, radius, op)| filter_extent(radius, op, longest_side).1.div_ceil(TILE)).collect(); + for index in (0..margins.len().saturating_sub(1)).rev() { + margins[index] += margins[index + 1]; } + + let mut previous: Option<(usize, Field)> = None; + for (&filter, &margin) in filters.iter().zip(&margins) { + let region = region_around(inp, tiles, margin)?; + let start = previous.as_ref().map(|(index, field)| (*index, field)); + let filtered = filter_region(inp, channels, below, id, job, effects, filter, region, start)?; + previous = Some((filter.0, filtered)); + } + previous.map(|(_, field)| field) +} + +/// The tile-aligned texel region `(x0, y0, w, h)` around `tiles` plus `margin` tiles, clipped to the set. +fn region_around(inp: &Inputs, tiles: &[(u32, u32)], margin: u32) -> Option<(u32, u32, u32, u32)> { + let (first_x, first_y) = tiles.iter().fold((u32::MAX, u32::MAX), |(min_x, min_y), tile| (min_x.min(tile.0), min_y.min(tile.1))); + let (last_x, last_y) = tiles.iter().fold((0, 0), |(max_x, max_y), tile| (max_x.max(tile.0), max_y.max(tile.1))); + let (x0, y0) = (first_x.saturating_sub(margin) * TILE, first_y.saturating_sub(margin) * TILE); + let (x1, y1) = (((last_x + 1 + margin) * TILE).min(inp.gbuf.width), ((last_y + 1 + margin) * TILE).min(inp.gbuf.height)); + let (w, h) = (x1.saturating_sub(x0), y1.saturating_sub(y0)); + (w > 0 && h > 0).then_some((x0, y0, w, h)) +} + +/// A neighbourhood filter's radius in whole texels and how many texels around a texel it reads. +fn filter_extent(radius: f32, op: Op, longest_side: u32) -> (u32, u32) { + // Clamped so a hostile radius can't overflow the region arithmetic + let radius_texels = radius.round().clamp(1.0, longest_side as f32) as u32; + + // Three box passes reach three radii; the gathering filters one radius plus a bilinear texel + let reach = if is_box_blur(op) { 3 * radius_texels } else { radius_texels + 1 }; + (radius_texels, reach) +} + +/// Whether neighbourhood filter `op` is computed from box blurs (the others gather samples). +fn is_box_blur(op: Op) -> bool { + matches!(op, Op::Blur(_) | Op::HighPass | Op::Bevel | Op::Glow(_)) +} + +/// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given. +#[allow(clippy::too_many_arguments)] +fn filter_region( + inp: &Inputs, + channels: &[Channel], + below: &Fields, + id: LayerId, + job: Job, + effects: &[Effect], + (index, radius, op): (usize, f32, Op), + (rx0, ry0, w, h): (u32, u32, u32, u32), + start: Option<(usize, &Field)>, +) -> Option { + let opacity = effects.iter().filter(|effect| effect.visible).nth(index).map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); + let (radius_texels, _) = filter_extent(radius, op, inp.gbuf.width.max(inp.gbuf.height)); let comps = match job { Job::Mask(_) => 1, Job::Content(_) => 4, }; - // Evaluate the stack before the filter, tile by tile (content premultiplied by coverage). + + // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage) + let (rx1, ry1) = (rx0 + w, ry0 + h); let region_tiles: Vec<(u32, u32)> = (ry0 / TILE..ry1.div_ceil(TILE)).flat_map(|y| (rx0 / TILE..rx1.div_ceil(TILE)).map(move |x| (x, y))).collect(); let parts: Vec> = region_tiles .par_iter() .map(|&(tx, ty)| { let full = anchor_plan(inp, id, channels, tx, ty, Some(below)); - let preview_tile = inp.preview.and_then(|p| p.alpha.tile(tx, ty)); + let preview_tile = inp.preview.and_then(|preview| preview.alpha.tile(tx, ty)); let mut mask = None; let mut nodes = Vec::new(); match job { - Job::Mask(m) => { - let Some(mut mp) = mask_plan(inp, id, m, tx, ty, None) else { return Vec::new() }; - mp.effects.truncate(k); - mask = Some(mp); + Job::Mask(layer_mask) => { + let Some(mut mask_stack) = mask_plan(inp, id, layer_mask, tx, ty, None) else { return Vec::new() }; + + mask_stack.effects.truncate(index); + mask_stack.start = start; + mask = Some(mask_stack); } - Job::Content(ch) => { - nodes = plan(inp, &[id], &[ch], tx, ty, 0, Some(below)); - if let Some(c) = nodes.first_mut().and_then(|n| n.chans.first_mut()) { - c.effects.truncate(k); - c.start = None; + Job::Content(channel) => { + nodes = plan(inp, &[id], &[channel], tx, ty, 0, Some(below)); + if let Some(chan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) { + chan.effects.truncate(index); + chan.start = start; } } } tile_texels(inp.gbuf, tx, ty) - .map(|(x, y, o)| { - let mut tex = Texel::new(inp, x, y, o, stroke_at(preview_tile, o)); + .map(|(x, y, offset)| { + let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview_tile, offset)); if !full.is_empty() { - tex.anchors_below(&full, id); + texel.anchors_below(&full, id); } - let v = match (&mask, nodes.first()) { - (Some(mp), _) => [tex.mask(mp), 0.0, 0.0, 0.0], - (None, Some(n)) => match n.chans.first().and_then(|c| tex.content(&n.content, c)) { - Some((v, cov)) => [v[0] * cov, v[1] * cov, v[2] * cov, cov], + let value = match (&mask, nodes.first()) { + (Some(mask_stack), _) => [texel.mask(mask_stack), 0.0, 0.0, 0.0], + (None, Some(node)) => match node.chans.first().and_then(|chan| texel.content(&node.content, chan)) { + Some((color, cov)) => [color[0] * cov, color[1] * cov, color[2] * cov, cov], None => [0.0; 4], }, (None, None) => [0.0; 4], }; - (x, y, v) + (x, y, value) }) .collect() }) .collect(); - // Scatter into the region, a row of tiles at a time (the region is tile aligned). - let n = (w * h) as usize; - let mut orig = vec![0.0f32; n * comps]; - let mut cover = vec![0.0f32; n]; + + // Scatter into the region, a row of tiles at a time (the region is tile aligned) + let texel_count = (w * h) as usize; + let mut orig = vec![0.0f32; texel_count * comps]; + let mut cover = vec![0.0f32; texel_count]; let row_tiles = (rx1.div_ceil(TILE) - rx0 / TILE).max(1) as usize; let band = (TILE * w) as usize; orig.par_chunks_mut(band * comps).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((orig, cover), row)| { - for &(x, y, v) in row.iter().flatten() { - let i = (((y - ry0) % TILE) * w + (x - rx0)) as usize; - if let (Some(c), Some(px)) = (cover.get_mut(i), orig.get_mut(i * comps..(i + 1) * comps)) { - *c = 1.0; - px.copy_from_slice(&v[..comps]); + for &(x, y, value) in row.iter().flatten() { + let texel = (((y - ry0) % TILE) * w + (x - rx0)) as usize; + if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), orig.get_mut(texel * comps..(texel + 1) * comps)) { + *covered = 1.0; + pixel.copy_from_slice(&value[..comps]); } } }); - // High pass centers on the channel's mid value (0 for signed channels like height). + + // High pass centers on the channel's mid value (0 for signed channels like height) let mid = match job { - Job::Content(ch) if ch.kind() == ChannelKind::Signed => 0.0, + Job::Content(channel) if channel.kind() == ChannelKind::Signed => 0.0, _ => 0.5, }; - // The filter at the radius of a tile filling `scale` of its atlas block (a smaller tile has - // fewer texels per UV unit, so its filters reach fewer texels). + + // A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels let filtered = |scale: f32| -> Vec { let res = ((inp.tile_res() as f32 * scale).round() as u32).max(1); - let r = neighbourhood(effects, res).map_or(r, |(_, radius, _)| radius.round().clamp(1.0, r as f32) as u32); - if !blurs { - return gather(op, &orig, &cover, comps, (rx0, ry0, w, h), r as f32, res, opacity); + let scaled_radius = neighbourhood_filters(effects, res) + .find(|filter| filter.0 == index) + .map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); + if !is_box_blur(op) { + return gather(op, &orig, &cover, comps, (rx0, ry0, w, h), scaled_radius as f32, res, opacity); } - // Weighted so uncovered texels don't bleed in. - let (wu, hu, ru) = (w as usize, h as usize, r as usize); + + // Weighted so uncovered texels don't bleed in + let (width, height, blur_radius) = (w as usize, h as usize, scaled_radius as usize); let mut weights = cover.clone(); - blur(&mut weights, wu, hu, ru); + blur(&mut weights, width, height, blur_radius); let mut data = orig.clone(); - for p in 0..comps { - let mut vals: Vec = orig.par_chunks(comps).map(|px| px.get(p).copied().unwrap_or(0.0)).collect(); - blur(&mut vals, wu, hu, ru); - data.par_chunks_mut(comps).zip(vals.par_iter()).zip(weights.par_iter()).for_each(|((px, v), wt)| { - // Content is premultiplied, so the mid value is too (coverage itself is kept). - let cov = if comps == 4 { px.get(3).copied().unwrap_or(0.0) } else { 1.0 }; - if *wt > 1e-6 - && let Some(slot) = px.get_mut(p) + for component in 0..comps { + let mut sums: Vec = orig.par_chunks(comps).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect(); + blur(&mut sums, width, height, blur_radius); + data.par_chunks_mut(comps).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| { + // Content is premultiplied, so the mid value is too (coverage itself is kept) + let cov = if comps == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + if *weight > 1e-6 + && let Some(slot) = pixel.get_mut(component) { - let (o, blurred) = (*slot, v / wt); - let filtered = match op { - Op::Blur(Some(amount)) => o + amount * (o - blurred), - Op::HighPass if p < 3 => o - blurred + mid * cov, - // Away from 0 by at most the value itself: 0 at the edge, full inside. - Op::Bevel if p < 3 => o.signum() * o.abs().min((2.0 * blurred * o.signum() - o.abs()).max(0.0)), - Op::Glow(amount) if p < 3 => o + amount * blurred, - Op::HighPass | Op::Bevel | Op::Glow(_) => o, + let (original, blurred) = (*slot, sum / weight); + let result = match op { + Op::Blur(Some(amount)) => original + amount * (original - blurred), + Op::HighPass if component < 3 => original - blurred + mid * cov, + // Away from 0 by at most the value itself: 0 at the edge, full inside + Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)), + Op::Glow(amount) if component < 3 => original + amount * blurred, + Op::HighPass | Op::Bevel | Op::Glow(_) => original, _ => blurred, }; - *slot = o + (filtered - o) * opacity; + *slot = original + (result - original) * opacity; } }); } data }; - // Each block keeps the result at its tile's scale (blocks are TILE aligned). + + // Each block keeps the result at its tile's scale (blocks are TILE aligned) let scales = inp.project.texture_set(inp.ts).map(TextureSet::block_scales).unwrap_or_default(); let mut levels: Vec = (ry0..ry1).step_by(TILE as usize).flat_map(|y| (rx0..rx1).step_by(TILE as usize).map(move |x| (x, y))).map(|(x, y)| scales.at(x, y)).collect(); levels.sort_by(f32::total_cmp); levels.dedup(); - let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(f, r)| (*f, r)); + let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(first, rest)| (*first, rest)); let mut data = filtered(first); for &scale in rest { let other = filtered(scale); let row = w as usize * comps; data.par_chunks_mut(row).zip(other.par_chunks(row)).enumerate().for_each(|(y, (dst, src))| { - for (x, (d, s)) in dst.chunks_mut(comps).zip(src.chunks(comps)).enumerate() { + for (x, (target, source)) in dst.chunks_mut(comps).zip(src.chunks(comps)).enumerate() { if scales.at(rx0 + x as u32, ry0 + y as u32) == scale { - d.copy_from_slice(s); + target.copy_from_slice(source); } } }); } + unpremultiply(&mut data, comps); Some(Field { x0: rx0, y0: ry0, w, h, comps, data }) } @@ -2348,6 +2399,55 @@ mod tests { } } + #[test] + fn a_mask_runs_every_neighbourhood_filter_in_order() { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 128); + fixture.project.texture_sets[0].resolution = 128; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }; + let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }; + let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); + let mut masked = |filters: &[Filter]| { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker.clone(), projection: Projection::default() })); + for filter in filters { + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(filter.clone()))); + } + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap() + }; + + let warped = masked(std::slice::from_ref(&warp)); + let blurred_then_warped = masked(&[Filter::Blur { radius: 64.0 }, warp]); + assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs"); + assert!(blurred_then_warped.iter().any(|value| *value > 0.05 && *value < 0.95), "the blur softens the checker before the warp moves it"); + } + + #[test] + fn a_content_stack_runs_every_neighbourhood_filter_in_order() { + let mut fixture = fixture(); + let layer = fill_layer(&mut fixture.project, [0.0; 3], 1.0); + let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(layer).unwrap().kind else { panic!("expected a fill layer") }; + + fill.sources.insert(Channel::BaseColor, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }); + let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }; + let warp_effect = content_fx(&mut fixture, layer, EffectKind::Filter(warp)); + let row = |fixture: &Fixture| -> Vec { + let composite = run(fixture, None); + (0..64).map(|x| composite.value(Channel::BaseColor, x, 20)[0]).collect() + }; + let warped = row(&fixture); + + content_fx(&mut fixture, layer, EffectKind::Filter(Filter::Blur { radius: 64.0 })); + let effects = &mut fixture.project.layer_mut(layer).unwrap().content_effects; + let warp_index = effects.iter().position(|effect| effect.id == warp_effect).unwrap(); + let warp_on_top = effects.remove(warp_index); + effects.push(warp_on_top); + let blurred_then_warped = row(&fixture); + assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs"); + } + #[test] fn blur_filter_softens_mask_edges() { let mut f = fixture(); From 297fad6fe789761728bc36688ac27c5af671a551 Mon Sep 17 00:00:00 2001 From: Chris Hassebrook Date: Fri, 6 Nov 2026 01:50:36 -0500 Subject: [PATCH 21/73] Helpful PR review guidelines doc for reviewers --- docs/helpful-pr-review-guidelines.md | 68 ++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 docs/helpful-pr-review-guidelines.md diff --git a/docs/helpful-pr-review-guidelines.md b/docs/helpful-pr-review-guidelines.md new file mode 100644 index 00000000..eebcb242 --- /dev/null +++ b/docs/helpful-pr-review-guidelines.md @@ -0,0 +1,68 @@ +# My PR review standards + +Review and improve the PR using these preferences. Follow the repository's instructions and keep changes focused on the problem being solved. + +## Correctness + +- Verify the claimed fix against the actual code and its callers +- Look for missed edge cases, incomplete fixes, and regressions +- Reproduce suspicious behavior locally when practical +- Make regression tests fail before the fix and pass afterward +- Confirm tests exercise the intended path, especially fallbacks and error handling + +## Optimization and simplicity + +- Prefer the smallest complete solution that is efficient and easy to understand +- Look for repeated calculations, expensive iterations, unnecessary allocations, and redundant data access +- Consider caching, batching, and parallelism when measurements justify their complexity and memory cost +- Measure relevant runtime, construction cost, and memory tradeoffs using representative workloads +- Check what the compiler already optimizes before replacing clear arithmetic with micro-optimizations +- Avoid speculative optimization, unnecessary dependencies, and abstractions that add more code than clarity + +## Clarity, naming, and spacing + +- Clean up the methods being changed, including their tests +- Use descriptive names that explain purpose; include units where useful +- Avoid cryptic abbreviations, misleading names, and unexplained production constants +- Keep control flow direct and share repeated logic when it makes the code simpler +- Separate logical steps with sensible blank lines so code is easy to scan +- Put a blank line after a multiline `let ... else` guard before the next statement; never place the next `let` directly after its closing `};` +- Keep related statements together and follow the repository's formatter + +## Source organization + +- Keep each class, enum, or struct in its own source file, with its implementation beside it +- Spell out the full type name in the filename; use the language's filename convention, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings` in Rust +- Use singular folder names, such as `map`, `setting`, or `tracing` +- Group related types into focused modules and share helpers where useful without collecting unrelated types into one large file + +## Comments + +- Use short, single-line comments or concise adjacent comments +- Avoid block comments and prose wrapped across multiple comment lines +- Explain intent or a non-obvious constraint rather than narrating the code +- No trailing punctuation on ordinary code comments +- Avoid overexplaining and remove stale or redundant comments +- Apply these standards to both production code and tests + +## Validation and reporting + +- Run relevant tests and required repository checks with the project's expected toolchain +- For comments or spacing alone, verify formatting and that executable code is unchanged +- Report concrete findings with locations, reproduction details, and practical impact +- Separate confirmed problems from hypotheses and optional improvements +- Give measured optimization results with workload and environment details +- State remaining limitations and distinguish existing failures from new ones + +## Review and commit workflow + +- Preserve unrelated work and leave changes unstaged for my manual review unless I ask otherwise +- Stage only when requested +- Wait for my explicit commit command before committing +- Do not push or post reviews or comments without explicit instructions +- When requested, provide a simple ready-to-post Markdown summary outside the repository and exclude it from the commit + +## Scope of method fixes + +- Whenever a method needs a fix, apply all of my review standards across the entire method, including existing code outside the immediate fix +- Ensure the whole method has sensible spacing between logical steps and concise, useful comments that follow the standards above From 19f75c3a00b9eb7635d4763f6ac4ccd657f66b03 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 07:00:56 +0000 Subject: [PATCH 22/73] Smart material previews on the preview orb Smart material shelf tiles and hover previews render the real material, applied with materials::apply to the baked preview orb and composited by the compositor, lit in a dark studio of soft boxes. MaskPreview becomes OrbPreview (masks and materials share one bake and one worker). Tiles show a loading icon until their preview arrives; the web takes one worker request per frame. preview::material keeps plain materials only. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lib.rs | 5 +- crates/engine/src/mask_preview.rs | 161 ---------- crates/engine/src/mask_preview_pixel.rs | 2 +- crates/engine/src/material_preview_pixel.rs | 16 + .../{mask_preview_camera.rs => orb_camera.rs} | 30 +- crates/engine/src/orb_preview.rs | 297 ++++++++++++++++++ crates/engine/src/preview.rs | 115 +++---- crates/geom/src/primitives.rs | 2 +- crates/ui-egui/src/lib.rs | 4 +- crates/ui-egui/src/mask_preview_image.rs | 2 +- crates/ui-egui/src/mask_shape.rs | 33 -- crates/ui-egui/src/material_preview_image.rs | 100 ++++++ crates/ui-egui/src/orb_shape.rs | 33 ++ crates/ui-egui/src/preview_image.rs | 73 +++-- crates/ui-egui/src/preview_request.rs | 10 +- crates/ui-egui/src/preview_worker.rs | 19 +- crates/ui-egui/src/shelf.rs | 49 +-- crates/ui-egui/src/shelf_preview.rs | 35 ++- crates/ui-egui/src/soft_box.rs | 48 +++ crates/ui-egui/src/thumbs.rs | 50 ++- crates/ui-egui/src/worker_preview.rs | 2 +- crates/ui-egui/tests/shelf_hover_preview.rs | 2 +- 22 files changed, 727 insertions(+), 361 deletions(-) delete mode 100644 crates/engine/src/mask_preview.rs create mode 100644 crates/engine/src/material_preview_pixel.rs rename crates/engine/src/{mask_preview_camera.rs => orb_camera.rs} (69%) create mode 100644 crates/engine/src/orb_preview.rs delete mode 100644 crates/ui-egui/src/mask_shape.rs create mode 100644 crates/ui-egui/src/material_preview_image.rs create mode 100644 crates/ui-egui/src/orb_shape.rs create mode 100644 crates/ui-egui/src/soft_box.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..cedf6cdb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -22,13 +22,14 @@ pub mod layer_cmds; pub mod layer_ops; pub mod link_cmds; pub mod mask_cmds; -pub mod mask_preview; -mod mask_preview_camera; mod mask_preview_pixel; pub mod material_lib; +mod material_preview_pixel; pub mod materials; pub mod materialx_cmds; pub mod meshmap_cmds; +mod orb_camera; +pub mod orb_preview; pub mod painting; pub mod path_tool; // Mesh reimport reads files: native only. diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs deleted file mode 100644 index a44757fc..00000000 --- a/crates/engine/src/mask_preview.rs +++ /dev/null @@ -1,161 +0,0 @@ -//! Smart mask previews share one baked [`primitives::preview_orb`] -//! Presets use `mask.smart.apply` and the compositor, matching document masks - -use serde_json::json; -use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; -use texturecraft_geom::glam::Vec3; -use texturecraft_geom::primitives; - -use crate::mask_preview_camera::MaskPreviewCamera; -pub use crate::mask_preview_pixel::MaskPreviewPixel; -use crate::{EngineError, Result, Session}; - -/// Bake resolution in texels; 256 loses the thin edge lines -const TEXTURE_PX: u32 = 512; -/// Camera rays per preview pixel along each axis (anti-aliased outline) -const SUPERSAMPLE: usize = 2; -/// Bound camera samples and output allocations for shelf previews -pub const MAX_PREVIEW_SIZE_PX: usize = 512; -/// AO and thickness rays per texel; thumbnail detail needs fewer than the default -const OCCLUSION_RAYS: u32 = 12; -/// Curvature rays per texel; thumbnail detail needs fewer than the default -const CURVATURE_RAYS: u32 = 12; -/// Radius relative to the bounding box; isolates panel edges from the round body -const CURVATURE_RADIUS: f32 = 0.005; -/// The mesh maps the smart mask generators read -const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; -/// Keep camera views for the thumbnail and hover preview sizes -const CAMERAS_KEPT: usize = 2; - -/// The baked preview shape and, per preview size, what its camera sees -pub struct MaskPreview { - session: Session, - layer: LayerId, - /// Cached camera views, least recently used first - cameras: Vec, -} - -impl MaskPreview { - /// Bake the preview shape once (previews of any size reuse it) - pub fn new() -> Result { - let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; - let set = session.doc.project.texture_set_mut(0)?; - set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; - set.bake.high_poly.use_low_as_high = true; - set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; - set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; - set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; - set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; - set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; - for map in BakedMap::ALL { - set.bake.maps.set_enabled(map, MAPS.contains(&map)); - } - let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; - session.bake_now(0, false)?; - - Ok(MaskPreview { session, layer, cameras: Vec::new() }) - } - - /// Row-major `size²` pixels, with None outside the shape - /// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] - pub fn render(&mut self, id: &str, size: usize) -> Option>> { - if !(1..=MAX_PREVIEW_SIZE_PX).contains(&size) { - return None; - } - - crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; - // Previews need no undo history; retaining snapshots grows memory across presets - self.session.undo.clear(); - - let camera = camera_for(&mut self.cameras, &self.session, size)?; - let values = self.session.mask_at(self.layer, &camera.texels)?; - - let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; - let pixels = (0..size * size) - .map(|i| { - let (x, y) = (i % size, i / size); - let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0); - for sy in 0..SUPERSAMPLE { - for sx in 0..SUPERSAMPLE { - let ray = (y * SUPERSAMPLE + sy) * camera.rays_per_side + x * SUPERSAMPLE + sx; - let Some(&Some((texel, n))) = camera.samples.get(ray) else { continue }; - - mask += values.get(texel).copied().unwrap_or(0.0); - normal += n; - hits += 1.0; - } - } - (hits > 0.0).then(|| MaskPreviewPixel { mask: mask / hits, normal: normal.normalize_or_zero(), coverage: hits / sub_pixels }) - }) - .collect(); - Some(pixels) - } -} - -/// Cache one camera per preview size, evicting the least recently used view -fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a MaskPreviewCamera> { - let rays_per_side = size * SUPERSAMPLE; - let camera = match cameras.iter().position(|c| c.rays_per_side == rays_per_side) { - Some(i) => cameras.remove(i), - None => MaskPreviewCamera::new(session, TEXTURE_PX, rays_per_side), - }; - if cameras.len() >= CAMERAS_KEPT { - cameras.remove(0); - } - - cameras.push(camera); - cameras.last() -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Mean absolute difference of the masks of two previews over the pixels both see - fn difference(a: &[Option], b: &[Option]) -> f32 { - let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); - pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 - } - - #[test] - fn invalid_preview_sizes_are_rejected_before_changing_the_shape() { - let session = Session::new_project("Mask preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); - let layer = session.doc.project.texture_set(0).unwrap().stack[0]; - let mut preview = MaskPreview { session, layer, cameras: Vec::new() }; - for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] { - assert!(preview.render("edges_sharp", size).is_none(), "size {size} should be rejected before rendering"); - assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera"); - assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask"); - } - } - - #[test] - fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() { - let size = 24; - let mut preview = MaskPreview::new().unwrap(); - for sm in crate::smart_masks::SMART_MASKS { - let px = preview.render(sm.id, size).unwrap_or_else(|| panic!("{}", sm.id)); - assert_eq!(px.len(), size * size, "{}", sm.id); - assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id); - let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect(); - assert!(seen.len() > size * size / 3, "{}: the shape fills the frame", sm.id); - for p in seen { - assert!((0.0..=1.0).contains(&p.mask) && (0.0..=1.0).contains(&p.coverage) && p.coverage > 0.0, "{}: {p:?}", sm.id); - assert!(p.normal.is_finite(), "{}: {p:?}", sm.id); - } - } - - let (edges, cavities) = (preview.render("edges_sharp", size).unwrap(), preview.render("dirt_cavities", size).unwrap()); - let shows = |px: &[Option]| px.iter().flatten().any(|p| p.mask > 0.5); - assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); - assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); - assert!(preview.render("nope", size).is_none()); - - let big = preview.render("edges_sharp", size * 3).unwrap(); - let mean = |px: &[Option]| px.iter().flatten().map(|p| p.mask).sum::() / px.iter().flatten().count().max(1) as f32; - assert_eq!(big.len(), size * size * 9); - assert!((mean(&big) - mean(&edges)).abs() < 0.05, "{} vs {}", mean(&big), mean(&edges)); - preview.render("edges_sharp", size * 2).unwrap(); - assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); - } -} diff --git a/crates/engine/src/mask_preview_pixel.rs b/crates/engine/src/mask_preview_pixel.rs index bcde5629..14ad5842 100644 --- a/crates/engine/src/mask_preview_pixel.rs +++ b/crates/engine/src/mask_preview_pixel.rs @@ -1,4 +1,4 @@ -//! One pixel of a smart mask preview (see [`crate::mask_preview::MaskPreview`]). +//! One pixel of a smart mask preview (see [`crate::orb_preview::OrbPreview::mask`]) use texturecraft_geom::glam::Vec3; diff --git a/crates/engine/src/material_preview_pixel.rs b/crates/engine/src/material_preview_pixel.rs new file mode 100644 index 00000000..7b83422e --- /dev/null +++ b/crates/engine/src/material_preview_pixel.rs @@ -0,0 +1,16 @@ +//! One pixel of a smart material preview (see [`crate::orb_preview::OrbPreview::material`]) + +use texturecraft_geom::glam::Vec3; + +use crate::preview::Sample; + +/// The material values seen at a preview pixel, with what a display needs to light the shape +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MaterialPreviewPixel { + /// Linear material values, averaged over the pixel + pub sample: Sample, + /// Surface normal in view space (+X right, +Y up, +Z towards the viewer) + pub normal: Vec3, + /// Fraction of the pixel the shape covers (0..=1, anti-aliased outline) + pub coverage: f32, +} diff --git a/crates/engine/src/mask_preview_camera.rs b/crates/engine/src/orb_camera.rs similarity index 69% rename from crates/engine/src/mask_preview_camera.rs rename to crates/engine/src/orb_camera.rs index ea3d6d1f..d0015361 100644 --- a/crates/engine/src/mask_preview_camera.rs +++ b/crates/engine/src/orb_camera.rs @@ -1,4 +1,4 @@ -//! Cached camera rays for one smart mask preview size +//! Cached camera rays for one preview orb size use std::collections::HashMap; @@ -11,11 +11,11 @@ use crate::Session; const CAMERA_PITCH_DEG: f32 = 35.0; const CAMERA_YAW_DEG: f32 = -34.4; -/// Index into [`MaskPreviewCamera::texels`] and view-space normal; None on a miss +/// Index into [`OrbCamera::texels`] and view-space normal; None on a miss pub(crate) type CameraSample = Option<(usize, Vec3)>; -/// What each ray of a square orthographic view of the preview shape sees -pub(crate) struct MaskPreviewCamera { +/// What each ray of a square orthographic view of the orb sees +pub(crate) struct OrbCamera { /// Rays along each side of the view pub rays_per_side: usize, /// The texels (x, y) the camera sees, each once @@ -24,12 +24,12 @@ pub(crate) struct MaskPreviewCamera { pub samples: Vec, } -impl MaskPreviewCamera { +impl OrbCamera { /// Trace a square orthographic view onto a `texture_px²` texture - pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> MaskPreviewCamera { - let (lo, hi) = session.mesh.bounds(); - let center = (lo + hi) * 0.5; - let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); + pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> OrbCamera { + let (min, max) = session.mesh.bounds(); + let center = (min + max) * 0.5; + let radius = session.mesh.positions.iter().map(|position| position.distance(center)).fold(0.0f32, f32::max); let pitch = CAMERA_PITCH_DEG.to_radians(); let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); @@ -40,9 +40,9 @@ impl MaskPreviewCamera { let mut texels = Vec::new(); let mut index_of = HashMap::new(); let samples = (0..rays_per_side * rays_per_side) - .map(|i| { + .map(|ray| { let side = rays_per_side as f32; - let ndc = Vec2::new(((i % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((i / rays_per_side) as f32 + 0.5) / side * 2.0); + let ndc = Vec2::new(((ray % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((ray / rays_per_side) as f32 + 0.5) / side * 2.0); // Start well outside the shape so every ray enters it from the front let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; let hit = session.bvh.closest(origin, forward, radius * 8.0)?; @@ -52,10 +52,12 @@ impl MaskPreviewCamera { texels.push(texel); texels.len() - 1 }); - let n = surface.nrm; - Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) + + let normal = surface.nrm; + Some((index, Vec3::new(normal.dot(right), normal.dot(up), -normal.dot(forward)))) }) .collect(); - MaskPreviewCamera { rays_per_side, texels, samples } + + OrbCamera { rays_per_side, texels, samples } } } diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs new file mode 100644 index 00000000..f29a247d --- /dev/null +++ b/crates/engine/src/orb_preview.rs @@ -0,0 +1,297 @@ +//! Smart mask and smart material previews share one baked [`primitives::preview_orb`] +//! Presets use `mask.smart.apply`, materials use [`materials::apply`], both read back from the compositor + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::json; +use texturecraft_core::{BakeResolution, BakedMap, Channel, CurvatureMethod, LayerId}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::primitives; +use texturecraft_texel::TILE; + +pub use crate::mask_preview_pixel::MaskPreviewPixel; +pub use crate::material_preview_pixel::MaterialPreviewPixel; +use crate::orb_camera::OrbCamera; +use crate::preview::Sample; +use crate::session::Document; +use crate::{EngineError, Result, Session, materials}; + +/// Bake resolution in texels; 256 loses the thin edge lines +const TEXTURE_PX: u32 = 512; +/// Camera rays per preview pixel along each axis (anti-aliased outline) +const SUPERSAMPLE: usize = 2; +/// Bound camera samples and output allocations for shelf previews +pub const MAX_PREVIEW_SIZE_PX: usize = 512; +/// AO and thickness rays per texel; thumbnail detail needs fewer than the default +const OCCLUSION_RAYS: u32 = 12; +/// Curvature rays per texel; thumbnail detail needs fewer than the default +const CURVATURE_RAYS: u32 = 12; +/// Radius relative to the bounding box; isolates panel edges from the round body +const CURVATURE_RADIUS: f32 = 0.005; +/// The mesh maps the smart mask generators read; smart materials build on the same presets +const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; +/// Keep camera views for the thumbnail and hover preview sizes +const CAMERAS_KEPT: usize = 2; +/// The channels a material preview shows, in [`Sample`] order +const MATERIAL_CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height]; +/// The orb's only texture set +const SET: usize = 0; + +/// The baked orb and, per preview size, what its camera sees +pub struct OrbPreview { + session: Session, + /// The layer smart masks are applied to + layer: LayerId, + /// The baked document and selection, restored before each material + bare: (Document, BTreeMap), + /// Cached camera views, least recently used first + cameras: Vec, +} + +impl OrbPreview { + /// Bake the orb once (previews of any size reuse it) + pub fn new() -> Result { + let mut session = Session::new_project("Orb preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; + let set = session.doc.project.texture_set_mut(SET)?; + set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; + set.bake.high_poly.use_low_as_high = true; + set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; + set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; + set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; + set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; + set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; + for map in BakedMap::ALL { + set.bake.maps.set_enabled(map, MAPS.contains(&map)); + } + let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; + session.bake_now(SET, false)?; + + let bare = (session.doc.clone(), session.selected.clone()); + Ok(OrbPreview { session, layer, bare, cameras: Vec::new() }) + } + + /// Row-major `size²` pixels of smart mask `id`, with None outside the shape + /// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + pub fn mask(&mut self, id: &str, size: usize) -> Option>> { + if !valid_size(size) { + return None; + } + + crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; + // Previews need no undo history; retaining snapshots grows memory across presets + self.session.undo.clear(); + + let camera = camera_for(&mut self.cameras, &self.session, size)?; + let values = self.session.mask_at(self.layer, &camera.texels)?; + + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..size * size) + .map(|pixel| { + let (mut mask_sum, mut normal_sum, mut hits) = (0.0, Vec3::ZERO, 0.0); + for (texel, normal) in pixel_hits(camera, size, pixel) { + mask_sum += values.get(texel).copied().unwrap_or(0.0); + normal_sum += normal; + hits += 1.0; + } + + (hits > 0.0).then(|| MaskPreviewPixel { mask: mask_sum / hits, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels }) + }) + .collect(); + Some(pixels) + } + + /// Row-major `size²` pixels of built-in material `id`, with None outside the shape + /// Returns None for unknown materials or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + pub fn material(&mut self, id: &str, size: usize) -> Option>> { + if !valid_size(size) { + return None; + } + + // Each material goes on the bare shape, not over the previous one + (self.session.doc, self.session.selected) = self.bare.clone(); + let applied = materials::apply(&mut self.session, id); + // Previews need no undo history; retaining snapshots grows memory across materials + self.session.undo.clear(); + applied.ok()?; + + let camera = camera_for(&mut self.cameras, &self.session, size)?; + let values = material_at(&self.session, &camera.texels)?; + + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..size * size) + .map(|pixel| { + let mut sum = Sample { base: [0.0; 3], metallic: 0.0, roughness: 0.0, height: 0.0 }; + let (mut normal_sum, mut hits) = (Vec3::ZERO, 0.0); + for (texel, normal) in pixel_hits(camera, size, pixel) { + let Some(value) = values.get(texel) else { continue }; + + sum.base = [0, 1, 2].map(|component| sum.base[component] + value.base[component]); + sum.metallic += value.metallic; + sum.roughness += value.roughness; + sum.height += value.height; + normal_sum += normal; + hits += 1.0; + } + + (hits > 0.0).then(|| { + let mean = Sample { + base: sum.base.map(|component| component / hits), + metallic: sum.metallic / hits, + roughness: sum.roughness / hits, + height: sum.height / hits, + }; + MaterialPreviewPixel { sample: mean, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels } + }) + }) + .collect(); + Some(pixels) + } +} + +/// Preview sizes the camera may allocate +fn valid_size(size: usize) -> bool { + (1..=MAX_PREVIEW_SIZE_PX).contains(&size) +} + +/// The rays through `pixel` of a `size²` preview that hit the shape, as (texel index, view-space normal) +fn pixel_hits(camera: &OrbCamera, size: usize, pixel: usize) -> impl Iterator + '_ { + let (x, y) = (pixel % size, pixel / size); + (0..SUPERSAMPLE * SUPERSAMPLE).filter_map(move |sub_pixel| { + let (sub_x, sub_y) = (sub_pixel % SUPERSAMPLE, sub_pixel / SUPERSAMPLE); + let ray = (y * SUPERSAMPLE + sub_y) * camera.rays_per_side + x * SUPERSAMPLE + sub_x; + camera.samples.get(ray).copied().flatten() + }) +} + +/// The material values at `texels`, compositing only the tiles that hold them +fn material_at(session: &Session, texels: &[(u32, u32)]) -> Option> { + let tiles: BTreeSet<(u32, u32)> = texels.iter().map(|(x, y)| (x / TILE, y / TILE)).collect(); + let tiles: Vec<(u32, u32)> = tiles.into_iter().collect(); + + session.with_inputs(SET, |inputs| { + let mut composite = texturecraft_compose::Composite::new(&MATERIAL_CHANNELS, TEXTURE_PX); + texturecraft_compose::composite_tiles(inputs, &mut composite, &tiles); + + let samples = texels + .iter() + .map(|&(x, y)| { + let [base, metallic, roughness, height] = MATERIAL_CHANNELS.map(|channel| composite.value(channel, x, y)); + Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] } + }) + .collect(); + Some(samples) + }) +} + +/// Cache one camera per preview size, evicting the least recently used view +fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a OrbCamera> { + let rays_per_side = size * SUPERSAMPLE; + let camera = match cameras.iter().position(|camera| camera.rays_per_side == rays_per_side) { + Some(index) => cameras.remove(index), + None => OrbCamera::new(session, TEXTURE_PX, rays_per_side), + }; + if cameras.len() >= CAMERAS_KEPT { + cameras.remove(0); + } + + cameras.push(camera); + cameras.last() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Mean absolute difference of the masks of two previews over the pixels both see + fn difference(a: &[Option], b: &[Option]) -> f32 { + let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); + pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 + } + + /// Mean mask value over the pixels a preview sees + fn mean_mask(pixels: &[Option]) -> f32 { + pixels.iter().flatten().map(|pixel| pixel.mask).sum::() / pixels.iter().flatten().count().max(1) as f32 + } + + #[test] + fn invalid_preview_sizes_are_rejected_before_changing_the_shape() { + let session = Session::new_project("Orb preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let layer = session.doc.project.texture_set(SET).unwrap().stack[0]; + let bare = (session.doc.clone(), session.selected.clone()); + let mut preview = OrbPreview { session, layer, bare, cameras: Vec::new() }; + let stack_size = preview.session.doc.project.texture_set(SET).unwrap().stack.len(); + for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] { + assert!(preview.mask("edges_sharp", size).is_none(), "size {size} should be rejected before rendering"); + assert!(preview.material("steel_painted_worn", size).is_none(), "size {size} should be rejected before rendering"); + assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera"); + assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask"); + assert_eq!(preview.session.doc.project.texture_set(SET).unwrap().stack.len(), stack_size, "invalid sizes must not apply a material"); + } + } + + #[test] + fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() { + let size = 24; + let mut preview = OrbPreview::new().unwrap(); + for smart_mask in crate::smart_masks::SMART_MASKS { + let id = smart_mask.id; + let pixels = preview.mask(id, size).unwrap_or_else(|| panic!("{id}")); + assert_eq!(pixels.len(), size * size, "{id}"); + assert!(pixels[0].is_none(), "{id}: the corners are outside the shape"); + + let seen: Vec<&MaskPreviewPixel> = pixels.iter().flatten().collect(); + assert!(seen.len() > size * size / 3, "{id}: the shape fills the frame"); + for pixel in seen { + assert!((0.0..=1.0).contains(&pixel.mask) && (0.0..=1.0).contains(&pixel.coverage) && pixel.coverage > 0.0, "{id}: {pixel:?}"); + assert!(pixel.normal.is_finite(), "{id}: {pixel:?}"); + } + } + + let (edges, cavities) = (preview.mask("edges_sharp", size).unwrap(), preview.mask("dirt_cavities", size).unwrap()); + let shows = |pixels: &[Option]| pixels.iter().flatten().any(|pixel| pixel.mask > 0.5); + assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); + assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); + assert!(preview.mask("nope", size).is_none()); + + // The same bake renders other sizes, showing the same mask + let big = preview.mask("edges_sharp", size * 3).unwrap(); + assert_eq!(big.len(), size * size * 9); + assert!((mean_mask(&big) - mean_mask(&edges)).abs() < 0.05, "{} vs {}", mean_mask(&big), mean_mask(&edges)); + + preview.mask("edges_sharp", size * 2).unwrap(); + assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); + } + + #[test] + fn smart_materials_render_on_the_orb_and_show_their_wear() { + let size = 24; + let mut preview = OrbPreview::new().unwrap(); + for material in materials::MATERIALS.iter().filter(|material| material.smart) { + let id = material.id; + let pixels = preview.material(id, size).unwrap_or_else(|| panic!("{id}")); + assert_eq!(pixels.len(), size * size, "{id}"); + assert!(pixels[0].is_none(), "{id}: the corners are outside the shape"); + + for pixel in pixels.iter().flatten() { + let sample = pixel.sample; + let values = sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]); + assert!(values.into_iter().all(f32::is_finite), "{id}: {pixel:?}"); + assert!(pixel.normal.is_finite() && pixel.coverage > 0.0, "{id}: {pixel:?}"); + } + } + assert!(preview.material("nope", size).is_none()); + + // Paint chipped at the edges shows the steel under it: the smart material is not its base + let (worn, steel) = (preview.material("steel_painted_worn", size).unwrap(), preview.material("steel", size).unwrap()); + let metallic_pixels = |pixels: &[Option]| pixels.iter().flatten().filter(|pixel| pixel.sample.metallic > 0.5).count(); + let (worn_metallic, steel_metallic) = (metallic_pixels(&worn), metallic_pixels(&steel)); + assert!(worn_metallic > 0 && worn_metallic < steel_metallic / 2, "bare steel only at the worn edges: {worn_metallic} of {steel_metallic}"); + + let base_colors = |pixels: &[Option]| pixels.iter().flatten().map(|pixel| pixel.sample.base).collect::>(); + assert_ne!(base_colors(&worn), base_colors(&steel)); + + // Each material starts from the bare orb: rendering another one in between changes nothing + preview.material("iron_rusted", size).unwrap(); + assert_eq!(preview.material("steel_painted_worn", size).unwrap(), worn); + } +} diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 5b72cea4..ce45b9ff 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -1,14 +1,8 @@ -//! Shelf previews: built-in materials evaluated on a unit sphere seen from +Z, without a mesh or -//! baked maps (generators that need mesh maps are approximated with world-space noise), and -//! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked -//! preview ([`crate::mask_preview`]). +//! Cheap shelf previews on a unit sphere: plain materials and library filters (smart ones use [`crate::orb_preview`]) use rayon::prelude::*; -use texturecraft_compose::pattern::{Coords, procedural, world_noise}; -use texturecraft_core::{ - Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, - Projection, Source, TextureSet, blend1, -}; +use texturecraft_compose::pattern::{Coords, procedural}; +use texturecraft_core::{Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, Source, TextureSet}; use texturecraft_geom::glam::{Vec2, Vec3}; use crate::materials::{Builder, build}; @@ -50,54 +44,13 @@ fn source(s: &Source, proj: &Projection, c: &Coords) -> Option<[f32; 3]> { } } -/// Approximate generator: mesh-map signals become world noise (a sphere has no edges or cavities). -fn generator(g: &Generator, c: &Coords) -> f32 { - let dir = Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y); - let wear = (world_noise(c.pos, 3.0, 91) - 0.5) * 2.2; - let cavity = (world_noise(c.pos, 3.0, 57) - 0.3).clamp(0.0, 1.0) + (1.0 - c.nrm.y) * 0.1; - let s = match g.kind { - GeneratorKind::Position => c.pos.dot(dir) * 0.5 + 0.5, - GeneratorKind::Direction => c.nrm.dot(dir) * 0.5 + 0.5, - GeneratorKind::EdgeWear => wear, - GeneratorKind::Curvature => 0.5 + wear * 0.5, - GeneratorKind::AmbientOcclusion => 1.0 - cavity, - _ => cavity, - }; - // Same thresholding as the compositor. - let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s }; - let soft = g.softness.max(1e-3); - let t = ((s - (1.0 - g.level.clamp(0.0, 1.0) - soft)) / (2.0 * soft)).clamp(0.0, 1.0); - let v = t * t * (3.0 - 2.0 * t); - if g.invert { 1.0 - v } else { v } -} - -fn mask(m: &Mask, c: &Coords) -> f32 { - if !m.enabled { - return 1.0; - } - let mut v = if m.background == MaskBackground::White { 1.0 } else { 0.0 }; - for e in m.effects.iter().filter(|e| e.visible) { - let val = match &e.kind { - EffectKind::Fill { source: s, projection } => source(s, projection, c).map(|x| x[0]), - EffectKind::Generator(g) => Some(generator(g, c)), - EffectKind::Levels(l) => Some(l.apply(v)), - EffectKind::Filter(Filter::Invert) => Some(1.0 - v), - _ => None, - }; - if let Some(val) = val { - let blended = if matches!(e.kind, EffectKind::Levels(_) | EffectKind::Filter(_)) { val } else { blend1(e.blend, v, val) }; - v += (blended - v) * e.opacity.clamp(0.0, 1.0); - } - } - v.clamp(0.0, 1.0) -} - const CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height]; -/// Preview of built-in material `id` (None for an unknown id). +/// Preview of plain material `id` (None for an unknown id or a smart material, whose masks need mesh maps) pub fn material(id: &str, size: usize) -> Option>> { + let plain = crate::materials::find(id).filter(|found| !found.smart)?; let mut project = Project::new("preview", ""); - let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).ok()?; + let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, plain.id).ok()?; // Pixels evaluate independently and big previews take long on one core let normals: Vec<_> = sphere_normals(size).collect(); @@ -106,23 +59,24 @@ pub fn material(id: &str, size: usize) -> Option>> { .map(|normal| { let at = coords(normal?); let mut values = CHANNELS.map(Channel::default_value); - for layer in layers.iter().filter(|l| l.visible) { + for layer in layers.iter().filter(|layer| layer.visible) { + // Plain materials are unmasked fills let LayerKind::Fill(fill) = &layer.kind else { continue }; - let coverage = layer.mask.as_ref().map_or(1.0, |m| mask(m, &at)); for (value, channel) in values.iter_mut().zip(CHANNELS) { - let layer_value = fill.sources.get(&channel).and_then(|s| source(s, &fill.projection, &at)); + let layer_value = fill.sources.get(&channel).and_then(|channel_source| source(channel_source, &fill.projection, &at)); if let (Some(blend), Some(layer_value)) = (layer.blend(channel), layer_value) { - let weight = coverage * blend.opacity.clamp(0.0, 1.0); - *value = [0, 1, 2].map(|k| value[k] + (layer_value[k] - value[k]) * weight); + let weight = blend.opacity.clamp(0.0, 1.0); + *value = [0, 1, 2].map(|component| value[component] + (layer_value[component] - value[component]) * weight); } } } - let [base, metal, rough, height] = values; - Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] }) + let [base, metallic, roughness, height] = values; + Some(Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] }) }) .collect(); + Some(samples) } @@ -196,21 +150,40 @@ pub fn filter(id: &str, size: usize) -> Option>> { mod tests { use super::*; + /// Whether every value of `sample` is finite + fn finite(sample: &Sample) -> bool { + sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite) + } + #[test] fn previews_cover_the_sphere_with_finite_values() { - for m in crate::materials::MATERIALS { - let px = material(m.id, 16).unwrap_or_else(|| panic!("{}", m.id)); - let center = px[8 * 16 + 8].unwrap_or_else(|| panic!("{}", m.id)); - assert!(center.base.iter().chain([¢er.metallic, ¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", m.id); - assert!(px[0].is_none(), "corners are outside the sphere"); + let size = 16; + for built_in in crate::materials::MATERIALS { + let id = built_in.id; + if built_in.smart { + assert!(material(id, size).is_none(), "{id}: smart materials preview on the orb"); + continue; + } + + let mut project = Project::new("preview", ""); + let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).unwrap(); + assert!(layers.iter().all(|layer| layer.mask.is_none()), "{id}: the sphere preview shows no masks"); + + let pixels = material(id, size).unwrap_or_else(|| panic!("{id}")); + let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}")); + assert!(finite(¢er), "{id}"); + assert!(pixels[0].is_none(), "corners are outside the sphere"); } - assert!(material("nope", 8).is_none() && filter("nope", 8).is_none()); - for f in crate::filter_lib::FILTERS { - let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id)); - let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id)); - assert!(center.base.iter().chain([¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", f.id); + assert!(material("nope", size).is_none() && filter("nope", size).is_none()); + + let size = 24; + for library_filter in crate::filter_lib::FILTERS { + let id = library_filter.id; + let pixels = filter(id, size).unwrap_or_else(|| panic!("{id}")); + let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}")); + assert!(finite(¢er), "{id}"); } - let (plain, warped) = (filter("levels", 24).unwrap(), filter("warp", 24).unwrap()); + let (plain, warped) = (filter("levels", size).unwrap(), filter("warp", size).unwrap()); assert!(plain != warped, "the warp shows in its preview"); } } diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs index 29bad947..69fab43b 100644 --- a/crates/geom/src/primitives.rs +++ b/crates/geom/src/primitives.rs @@ -201,7 +201,7 @@ const ORB_CUT: f32 = 0.8; /// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius. const ORB_PANEL_VALLEY: f32 = 0.88; -/// The smart mask preview shape: a sphere cut flat by a cube on six sides, on a thin round base. +/// The preview orb of the smart mask and smart material previews: a sphere cut flat by a cube on six sides, on a thin round base /// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly /// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys /// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 375ff1ba..f383c197 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -17,8 +17,9 @@ pub mod gpu; pub mod i18n; pub mod keymap; mod mask_preview_image; -mod mask_shape; +mod material_preview_image; pub mod menus; +mod orb_shape; pub mod parity; mod preview_image; mod preview_request; @@ -27,6 +28,7 @@ pub mod profile; pub mod render_mode; pub mod shelf; pub mod shelf_preview; +mod soft_box; pub mod state; pub mod theme; pub mod thumbs; diff --git a/crates/ui-egui/src/mask_preview_image.rs b/crates/ui-egui/src/mask_preview_image.rs index 4418d099..de7368df 100644 --- a/crates/ui-egui/src/mask_preview_image.rs +++ b/crates/ui-egui/src/mask_preview_image.rs @@ -2,7 +2,7 @@ use egui::{Color32, ColorImage}; use texturecraft_engine::geom::glam::Vec3; -use texturecraft_engine::mask_preview::MaskPreviewPixel; +use texturecraft_engine::orb_preview::MaskPreviewPixel; use texturecraft_engine::texel::linear_to_srgb; /// View-space lighting uses an upper-left key and a weaker right fill diff --git a/crates/ui-egui/src/mask_shape.rs b/crates/ui-egui/src/mask_shape.rs deleted file mode 100644 index c99a9b1c..00000000 --- a/crates/ui-egui/src/mask_shape.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! The smart mask preview shape, baked on first use - -use texturecraft_engine::mask_preview::MaskPreview; - -/// Whether the smart mask preview shape is baked -#[derive(Default)] -pub enum MaskShape { - #[default] - NotBaked, - /// Box the large session to keep the unbaked worker small - Baked(Box), - /// The bake failed; smart mask previews stay empty - Failed, -} - -impl MaskShape { - /// Bake on first use; retain failure to avoid retrying every frame - pub fn get(&mut self) -> Option<&mut MaskPreview> { - if matches!(self, MaskShape::NotBaked) { - *self = match MaskPreview::new() { - Ok(preview) => MaskShape::Baked(Box::new(preview)), - Err(e) => { - log::warn!("smart mask previews: {e}"); - MaskShape::Failed - } - }; - } - match self { - MaskShape::Baked(preview) => Some(preview), - MaskShape::NotBaked | MaskShape::Failed => None, - } - } -} diff --git a/crates/ui-egui/src/material_preview_image.rs b/crates/ui-egui/src/material_preview_image.rs new file mode 100644 index 00000000..bc232b75 --- /dev/null +++ b/crates/ui-egui/src/material_preview_image.rs @@ -0,0 +1,100 @@ +//! Shading of the smart material previews: a dark studio whose soft boxes show in reflections and light the diffuse color + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::orb_preview::MaterialPreviewPixel; +use texturecraft_engine::texel::linear_to_srgb; + +use crate::preview_image::{aces, bumped_normal, height_slope, preview_radius}; +use crate::soft_box::{SoftBox, smoothstep}; + +/// The studio's soft boxes: a key at the upper right, a fill at the left and a rim light above and behind +const SOFT_BOXES: [SoftBox; 3] = [ + SoftBox { direction: [0.55, 0.75, 0.35], radius_rad: 0.6, intensity: 2.6 }, + SoftBox { direction: [-0.95, 0.2, 0.1], radius_rad: 0.7, intensity: 0.9 }, + SoftBox { direction: [0.1, 0.9, -0.45], radius_rad: 0.35, intensity: 1.6 }, +]; +/// The studio's backdrop brightness straight down and straight up (linear) +const FLOOR: f32 = 0.03; +const CEILING: f32 = 0.16; +/// The lowest roughness shaded (a perfect mirror would show the soft boxes' hard edges) +const MIN_ROUGHNESS: f32 = 0.02; +/// Reflectance of dielectrics at normal incidence +const DIELECTRIC_F0: f32 = 0.04; +/// Exposure before tone mapping +const EXPOSURE: f32 = 1.4; + +/// A smart material preview (sRGB, transparent off the shape) from `size²` preview pixels; height bumps the normals +pub fn material_preview_image(size: usize, pixels: &[Option]) -> ColorImage { + let radius = preview_radius(size); + let height = |index: usize| pixels.get(index).copied().flatten().map(|pixel| pixel.sample.height); + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (index, (out, pixel)) in image.pixels.iter_mut().zip(pixels).enumerate() { + let Some(pixel) = pixel else { continue }; + + let sample = pixel.sample; + let normal = bumped_normal(pixel.normal, height_slope(size, index, sample.height, height), radius); + let roughness = sample.roughness.max(MIN_ROUGHNESS); + let normal_dot_view = normal.z.max(0.0); + // Mirror the direction towards the viewer (+Z) about the normal + let reflected = (2.0 * normal_dot_view * normal - Vec3::Z).normalize_or_zero(); + let specular_light = reflected_light(reflected, roughness); + let diffuse_light = diffuse_light(normal); + // Schlick's Fresnel term, damped on rough surfaces below + let fresnel = (1.0 - normal_dot_view).powi(5); + + let color = [0, 1, 2].map(|component| { + let base = sample.base[component]; + let f0 = DIELECTRIC_F0 + (base - DIELECTRIC_F0) * sample.metallic; + let reflectance = f0 + ((1.0 - roughness).max(f0) - f0) * fresnel; + let linear = reflectance * specular_light + base * (1.0 - sample.metallic) * (1.0 - reflectance) * diffuse_light; + (linear_to_srgb(aces(linear * EXPOSURE)) * 255.0 + 0.5) as u8 + }); + let alpha = (pixel.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(color[0], color[1], color[2], alpha); + } + image +} + +/// How far unit direction component `y` points up: 0 straight down, 1 straight up +fn upward(y: f32) -> f32 { + y * 0.5 + 0.5 +} + +/// The backdrop's brightness `upward` of the way from the floor (0) to the ceiling (1) +fn backdrop(upward: f32) -> f32 { + FLOOR + (CEILING - FLOOR) * upward +} + +/// The studio seen along unit direction `view` by a surface of `roughness` +fn reflected_light(view: Vec3, roughness: f32) -> f32 { + // A soft horizon: reflections sweep from floor to ceiling smoothly + backdrop(smoothstep(upward(view.y))) + SOFT_BOXES.iter().map(|soft_box| soft_box.reflected(view, roughness)).sum::() +} + +/// The light reaching a diffuse surface with unit normal `normal` +fn diffuse_light(normal: Vec3) -> f32 { + backdrop(upward(normal.y)) + SOFT_BOXES.iter().map(|soft_box| soft_box.diffuse(normal)).sum::() +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::preview::Sample; + + use super::*; + + #[test] + fn the_studio_lights_the_shape_from_the_upper_right() { + let polished_metal = Sample { base: [0.9; 3], metallic: 1.0, roughness: 0.3, height: 0.0 }; + let facing = |normal: Vec3| Some(MaterialPreviewPixel { sample: polished_metal, normal: normal.normalize(), coverage: 1.0 }); + // Halfway between the viewer and the key light, a mirror reflects the key + let towards_the_key = SOFT_BOXES[0].unit_direction() + Vec3::Z; + let pixels = [facing(towards_the_key), facing(Vec3::new(-0.3, -0.9, 0.3)), None, None]; + + let image = material_preview_image(2, &pixels); + let [lit, unlit, outside] = [0, 1, 2].map(|index| image.pixels[index]); + assert!(lit.r() > 200 && unlit.r() < 80, "the key light's reflection shows: {lit:?} vs {unlit:?}"); + assert_eq!((lit.a(), outside.a()), (255, 0), "opaque on the shape, transparent outside"); + } +} diff --git a/crates/ui-egui/src/orb_shape.rs b/crates/ui-egui/src/orb_shape.rs new file mode 100644 index 00000000..3d220a5c --- /dev/null +++ b/crates/ui-egui/src/orb_shape.rs @@ -0,0 +1,33 @@ +//! The preview orb of the smart mask and smart material previews, baked on first use + +use texturecraft_engine::orb_preview::OrbPreview; + +/// Whether the preview orb is baked +#[derive(Default)] +pub enum OrbShape { + #[default] + NotBaked, + /// Box the large session to keep the unbaked worker small + Baked(Box), + /// The bake failed; previews on the orb stay empty + Failed, +} + +impl OrbShape { + /// Bake on first use; retain failure to avoid retrying every frame + pub fn get(&mut self) -> Option<&mut OrbPreview> { + if matches!(self, OrbShape::NotBaked) { + *self = match OrbPreview::new() { + Ok(preview) => OrbShape::Baked(Box::new(preview)), + Err(e) => { + log::warn!("preview orb: {e}"); + OrbShape::Failed + } + }; + } + match self { + OrbShape::Baked(preview) => Some(preview), + OrbShape::NotBaked | OrbShape::Failed => None, + } + } +} diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index f689c85d..9b753b74 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -3,6 +3,7 @@ use egui::{Color32, ColorImage}; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; use texturecraft_engine::paint::{BrushSettings, Shape}; use texturecraft_engine::preview::{self, Sample}; @@ -12,6 +13,14 @@ use texturecraft_engine::texel::linear_to_srgb; const PROCEDURAL_SCALE: f32 = 3.0; /// Samples per pixel along each axis of the alpha swatches const ALPHA_SUPERSAMPLE: usize = 2; +/// Normal tilt per height step, relative to the shape's radius in pixels +const BUMP_PER_RADIUS: f32 = 0.75; +/// Exposure of the shaded previews before tone mapping +const EXPOSURE: f32 = 1.4; +/// Gap between a preview's shape and the image edge in pixels +const SHAPE_MARGIN_PX: f32 = 1.0; +/// Guards the normal division against a zero vector +const MIN_NORMAL_LENGTH: f32 = 1e-6; /// Linear shading for view-space normal `n`, viewed along +Z pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { @@ -52,28 +61,52 @@ pub fn aces(x: f32) -> f32 { /// Shade row-major `size²` samples with height bumps and a transparent background pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { - let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); - let r = (size as f32 * 0.5 - 1.0).max(0.5); - let h = |x: Option, y: Option| { - let (x, y) = (x.filter(|x| *x < size)?, y?); - samples.get(y.checked_mul(size)?.checked_add(x)?).copied().flatten().map(|s| s.height) - }; - for (i, n) in preview::sphere_normals(size).enumerate() { - let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + let radius = preview_radius(size); + let height = |index: usize| samples.get(index).copied().flatten().map(|sample| sample.height); - let (x, y) = (i % size, i / size); - let c = s.height; - // Image Y points down; the shading normal uses Y up - let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); - let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); - let k = r * 0.5 * 1.5; - let b = [n.x - dx * k, n.y - dy * k, n.z]; - let len = (b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt().max(1e-6); - let col = shade(b.map(|v| v / len), s.base, s.metallic, s.roughness).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0 + 0.5) as u8); - let edge = ((1.0 - (n.x * n.x + n.y * n.y).sqrt()) * r).clamp(0.0, 1.0); - img.pixels[i] = Color32::from_rgba_unmultiplied(col[0], col[1], col[2], (edge * 255.0) as u8); + for (index, normal) in preview::sphere_normals(size).enumerate() { + let (Some(normal), Some(Some(sample))) = (normal, samples.get(index)) else { continue }; + + // Anti-aliased outline: opaque from one pixel inside the rim + let coverage = ((1.0 - (normal.x * normal.x + normal.y * normal.y).sqrt()) * radius).clamp(0.0, 1.0); + image.pixels[index] = lit_pixel(normal, height_slope(size, index, sample.height, height), radius, sample, coverage); } - img + image +} + +/// Radius in pixels of the shape filling a `size²` preview +pub(crate) fn preview_radius(size: usize) -> f32 { + (size as f32 * 0.5 - SHAPE_MARGIN_PX).max(0.5) +} + +/// Height change per pixel rightwards and upwards at `pixel`; None heights count as `center` +pub(crate) fn height_slope(size: usize, pixel: usize, center: f32, height: impl Fn(usize) -> Option) -> [f32; 2] { + let (x, y) = (pixel % size, pixel / size); + let at = |x: Option, y: Option| { + let (x, y) = (x.filter(|x| *x < size)?, y?); + height(y.checked_mul(size)?.checked_add(x)?) + }; + + // Image Y points down; the shading normal uses Y up + let right = at(Some(x + 1), Some(y)).unwrap_or(center) - at(x.checked_sub(1), Some(y)).unwrap_or(center); + let up = at(Some(x), y.checked_sub(1)).unwrap_or(center) - at(Some(x), Some(y + 1)).unwrap_or(center); + [right, up] +} + +/// Tilt a view-space normal by the height `slope` on a shape of `radius` pixels +pub(crate) fn bumped_normal(normal: Vec3, slope: [f32; 2], radius: f32) -> Vec3 { + let bump = radius * BUMP_PER_RADIUS; + let bumped = [normal.x - slope[0] * bump, normal.y - slope[1] * bump, normal.z]; + let length = (bumped[0] * bumped[0] + bumped[1] * bumped[1] + bumped[2] * bumped[2]).sqrt().max(MIN_NORMAL_LENGTH); + Vec3::from(bumped.map(|component| component / length)) +} + +/// One sphere pixel of `sample`, bumped by `slope` and `coverage` opaque +fn lit_pixel(normal: Vec3, slope: [f32; 2], radius: f32, sample: &Sample, coverage: f32) -> Color32 { + let linear = shade(bumped_normal(normal, slope, radius).to_array(), sample.base, sample.metallic, sample.roughness); + let color = linear.map(|component| (linear_to_srgb(aces(component * EXPOSURE)) * 255.0 + 0.5) as u8); + Color32::from_rgba_unmultiplied(color[0], color[1], color[2], (coverage * 255.0) as u8) } /// Grayscale `size²` swatch of procedural `kind` diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index 71c7870b..7797a7e3 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -3,7 +3,8 @@ use egui::ColorImage; use crate::mask_preview_image::mask_preview_image; -use crate::mask_shape::MaskShape; +use crate::material_preview_image::material_preview_image; +use crate::orb_shape::OrbShape; use crate::shelf_preview::ShelfPreview; /// Render `preview` at `size_px²`; the answer comes back under `key` @@ -18,11 +19,12 @@ pub struct PreviewRequest { } impl PreviewRequest { - /// Render the asset, baking the mask shape on first use + /// Render the asset, baking the orb on first use for smart masks and smart materials /// Unknown assets and failed bakes return None - pub fn render(&self, shape: &mut MaskShape) -> Option { + pub fn render(&self, shape: &mut OrbShape) -> Option { match &self.preview { - ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.render(id, self.size_px)?)), + ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.mask(id, self.size_px)?)), + ShelfPreview::SmartMaterial(id) => Some(material_preview_image(self.size_px, &shape.get()?.material(id, self.size_px)?)), preview => preview.image(self.size_px), } } diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs index a3d2cc8f..1fe89353 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -2,7 +2,7 @@ //! Web requests render synchronously on the UI thread #[cfg(target_arch = "wasm32")] -use crate::mask_shape::MaskShape; +use crate::orb_shape::OrbShape; use crate::preview_request::PreviewRequest; /// Request key and rendered image; None on failure @@ -18,7 +18,7 @@ pub enum PreviewWorker { Running { requests: std::sync::mpsc::Sender, results: std::sync::mpsc::Receiver }, /// The web: requests render as they are made #[cfg(target_arch = "wasm32")] - Inline { shape: MaskShape, results: Vec }, + Inline { shape: OrbShape, results: Vec }, /// The worker could not start or stopped; requests are refused // The web has no thread to stop #[cfg_attr(target_arch = "wasm32", allow(dead_code))] @@ -89,7 +89,7 @@ impl PreviewWorker { use std::collections::VecDeque; use std::sync::mpsc::channel; - use crate::mask_shape::MaskShape; + use crate::orb_shape::OrbShape; let (requests, request_rx) = channel::(); let (result_tx, results) = channel(); @@ -101,7 +101,7 @@ impl PreviewWorker { if let Err(e) = &pool { log::warn!("shelf previews share the global thread pool: {e}"); } - let mut shape = MaskShape::default(); + let mut shape = OrbShape::default(); let mut queue = VecDeque::new(); loop { if queue.is_empty() { @@ -136,7 +136,7 @@ impl PreviewWorker { /// Render inline (no threads on the web) #[cfg(target_arch = "wasm32")] fn start(_ctx: &egui::Context) -> PreviewWorker { - PreviewWorker::Inline { shape: MaskShape::default(), results: Vec::new() } + PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() } } } @@ -170,23 +170,26 @@ mod tests { ("unknown material", ShelfPreview::Material("nope")), ("mask", ShelfPreview::SmartMask(SMART_MASKS[0].id)), ("unknown mask", ShelfPreview::SmartMask("nope")), + ("smart material", ShelfPreview::SmartMaterial("steel_painted_worn")), + ("unknown smart material", ShelfPreview::SmartMaterial("nope")), ]; + let requests_sent = requests.len(); for (key, preview) in requests { assert!(worker.request(&ctx, PreviewRequest { key: key.into(), preview, size_px, hover: false }), "{key}"); } let mut answers = HashMap::new(); let start = Instant::now(); - while answers.len() < 4 && start.elapsed() < Duration::from_secs(120) { + while answers.len() < requests_sent && start.elapsed() < Duration::from_secs(120) { answers.extend(worker.poll()); std::thread::sleep(Duration::from_millis(10)); } - for key in ["material", "mask"] { + for key in ["material", "mask", "smart material"] { let image = answers.get(key).and_then(Option::as_ref).unwrap_or_else(|| panic!("{key}: {answers:?}")); assert_eq!(image.size, [size_px, size_px], "{key}"); } - for key in ["unknown material", "unknown mask"] { + for key in ["unknown material", "unknown mask", "unknown smart material"] { assert!(matches!(answers.get(key), Some(None)), "{key}: {answers:?}"); } assert!(!worker.is_stopped()); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 46ced908..5d876249 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -12,8 +12,8 @@ use texturecraft_engine::filter_lib::FILTERS; #[cfg(not(target_arch = "wasm32"))] use texturecraft_engine::formats::mcmat::MCMAT_EXT; use texturecraft_engine::geom::glam::Vec2; -use texturecraft_engine::mask_preview::MAX_PREVIEW_SIZE_PX; use texturecraft_engine::materials::MATERIALS; +use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; use texturecraft_engine::paint::alphas; use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; use texturecraft_engine::smart_masks::SMART_MASKS; @@ -34,8 +34,9 @@ const TILE_ROUNDING: f32 = 3.0; /// The thumbnail's size in a tile and its center below the tile's top, in points const THUMBNAIL_SIZE: f32 = 56.0; const THUMBNAIL_CENTER_Y: f32 = 32.0; -/// A placeholder disc's radius relative to the thumbnail's width -const PLACEHOLDER_RADIUS: f32 = 0.45; +/// Loading icon size relative to the thumbnail width, and its opacity over the dim text color +const LOADING_ICON_SCALE: f32 = 0.9; +const LOADING_ICON_OPACITY: f32 = 0.5; /// A tile label's font size, its gap below the thumbnail and its total side margin, in points const LABEL_FONT_SIZE: f32 = 9.5; const LABEL_GAP: f32 = 3.0; @@ -300,20 +301,22 @@ fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'st out } -/// Built-in materials (or smart materials), grouped by category. +/// Built-in materials or smart materials, grouped by category fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, smart: bool, name: &str) { - let shown: Vec<_> = MATERIALS.iter().filter(|m| m.smart == smart && matches(filter, &[m.label, m.category, m.id])).collect(); + let shown: Vec<_> = + MATERIALS.iter().filter(|material| material.smart == smart && matches(filter, &[material.label, material.category, material.id])).collect(); if shown.is_empty() { return; } + title(ui, name); - for cat in categories(&shown, |m| m.category) { - header(ui, cat); + for category in categories(&shown, |material| material.category) { + header(ui, category); tiles(ui, |ui| { - for m in shown.iter().filter(|m| m.category == cat) { - let tex = app.thumbs.material(ctx, m.id); - let asset = Asset::Material(m.id); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Material(m.id), m.label, Some(&asset)).clicked() { + for material in shown.iter().filter(|material| material.category == category) { + let texture = app.thumbs.material(ctx, material.id); + let asset = Asset::Material(material.id); + if tile(ui, &mut app.thumbs, texture.as_ref(), || ShelfPreview::material(material.id), material.label, Some(&asset)).clicked() { apply(app, &asset); } } @@ -623,8 +626,9 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev let preview = preview(); let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; - // High display scales must respect the mask camera's allocation limit - let size_px = if matches!(&preview, ShelfPreview::SmartMask(_)) { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; + // High display scales must respect the orb camera's allocation limit + let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_)); + let size_px = if on_the_orb { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; // Scrolling moves tiles beneath a stationary pointer let idle_seconds = ui.input(|input| if input.is_scrolling() { 0.0 } else { input.pointer.time_since_last_movement().min(input.time_since_last_scroll()) }); @@ -636,14 +640,21 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev thumbs.rendered_big(ctx, &preview, size_px) } -/// `tex` drawn into `rect`, or a placeholder disc while it renders -fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { - match tex { - Some(t) => { - painter.image(t.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); +/// `texture` drawn into `rect`, or a dim loading icon while it renders +fn thumbnail(painter: &egui::Painter, texture: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { + match texture { + Some(texture) => { + painter.image(texture.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); } None => { - painter.circle_filled(rect.center(), rect.width() * PLACEHOLDER_RADIUS, tk.row_hover); + let font = egui::FontId::proportional(rect.width() * LOADING_ICON_SCALE); + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + egui_phosphor::regular::ARROWS_CLOCKWISE, + font, + tk.text_dim.gamma_multiply(LOADING_ICON_OPACITY), + ); } } } diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index a23ffb32..b512f250 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use egui::ColorImage; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::materials; use texturecraft_engine::paint::BrushSettings; use texturecraft_engine::paint::alphas::LibraryAlpha; use texturecraft_engine::paint::presets::BrushPreset; @@ -14,9 +15,11 @@ use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_ /// The asset a shelf tile previews pub enum ShelfPreview { - /// A built-in material or smart material on a sphere + /// A built-in plain material on a sphere Material(&'static str), - /// Smart mask rendering requires the worker's baked shape + /// Smart material rendering requires the worker's baked orb + SmartMaterial(&'static str), + /// Smart mask rendering requires the worker's baked orb SmartMask(&'static str), /// A library filter on a sample material on a sphere Filter(&'static str), @@ -31,10 +34,19 @@ pub enum ShelfPreview { } impl ShelfPreview { + /// Smart materials preview on the orb, plain materials on a sphere + pub fn material(id: &'static str) -> ShelfPreview { + match materials::find(id) { + Some(found) if found.smart => ShelfPreview::SmartMaterial(id), + Some(_) | None => ShelfPreview::Material(id), + } + } + /// The cache key of the preview (one per asset) pub fn key(&self) -> String { match self { ShelfPreview::Material(id) => format!("mat:{id}"), + ShelfPreview::SmartMaterial(id) => format!("smart-mat:{id}"), ShelfPreview::SmartMask(id) => format!("mask:{id}"), ShelfPreview::Filter(id) => format!("filter:{id}"), ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), @@ -45,11 +57,11 @@ impl ShelfPreview { } /// Render a `size²` image; unknown assets return None - /// Smart masks return None here because their bake belongs to the worker + /// Smart masks and smart materials return None here because their bake belongs to the worker pub fn image(&self, size: usize) -> Option { match self { ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), - ShelfPreview::SmartMask(_) => None, + ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_) => None, ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), @@ -86,14 +98,23 @@ mod tests { let key = preview.key(); let image = preview.image(BIG_PX).unwrap_or_else(|| panic!("{key}")); assert_eq!(image.size, [BIG_PX, BIG_PX], "{key}"); - assert!(image.pixels.iter().any(|c| c.a() > 0 && c.r().max(c.g()).max(c.b()) > 0), "{key}: something shows"); + assert!(image.pixels.iter().any(|color| color.a() > 0 && color.r().max(color.g()).max(color.b()) > 0), "{key}: something shows"); } let finite = |samples: Vec>| { - samples.iter().flatten().all(|s| s.base.iter().chain([&s.metallic, &s.roughness, &s.height]).all(|v| v.is_finite())) + samples.iter().flatten().all(|sample| sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite)) }; assert!(finite(preview::material(MATERIALS[0].id, BIG_PX).unwrap_or_default())); assert!(finite(preview::filter(FILTERS[0].id, BIG_PX).unwrap_or_default())); - assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked shape"); + assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked orb"); + assert!(ShelfPreview::SmartMaterial("steel_painted_worn").image(BIG_PX).is_none(), "smart materials need the baked orb"); + } + + #[test] + fn smart_materials_and_only_they_preview_on_the_orb() { + for material in MATERIALS { + let on_the_orb = matches!(ShelfPreview::material(material.id), ShelfPreview::SmartMaterial(_)); + assert_eq!(on_the_orb, material.smart, "{}", material.id); + } } } diff --git a/crates/ui-egui/src/soft_box.rs b/crates/ui-egui/src/soft_box.rs new file mode 100644 index 00000000..9c2c8391 --- /dev/null +++ b/crates/ui-egui/src/soft_box.rs @@ -0,0 +1,48 @@ +//! A soft box of the smart material preview studio (see [`crate::material_preview_image`]) + +use texturecraft_engine::geom::glam::Vec3; + +/// How much roughness widens a soft box's reflection, in radians per unit of roughness +const BLUR_RAD_PER_ROUGHNESS: f32 = 1.1; +/// A reflected disc's soft edge: this share of its reflected radius plus a minimum in radians +const EDGE_SOFTNESS: f32 = 0.25; +const EDGE_SOFTNESS_MIN_RAD: f32 = 0.02; +/// The share of a soft box's light that reaches a diffuse surface facing it +const DIFFUSE_SHARE: f32 = 0.9; + +/// A round area light far away, seen as a disc in reflections +pub struct SoftBox { + /// Direction towards the light in view space (+X right, +Y up, +Z towards the viewer), not normalized + pub direction: [f32; 3], + /// Angular radius of the disc in radians + pub radius_rad: f32, + /// Brightness of the disc (linear) + pub intensity: f32, +} + +impl SoftBox { + /// The unit direction towards the light + pub fn unit_direction(&self) -> Vec3 { + Vec3::from(self.direction).normalize_or_zero() + } + + /// The light seen along unit direction `view` by a surface of `roughness`: rougher surfaces see the disc wider and dimmer (the same light spread out) + pub fn reflected(&self, view: Vec3, roughness: f32) -> f32 { + let reflected_radius_rad = self.radius_rad.hypot(roughness * BLUR_RAD_PER_ROUGHNESS); + let angle_rad = view.dot(self.unit_direction()).clamp(-1.0, 1.0).acos(); + let edge_width_rad = EDGE_SOFTNESS * reflected_radius_rad + EDGE_SOFTNESS_MIN_RAD; + let inside = smoothstep((reflected_radius_rad - angle_rad) / edge_width_rad); + self.intensity * (self.radius_rad / reflected_radius_rad).powi(2) * inside + } + + /// The light reaching a diffuse surface with unit normal `normal` + pub fn diffuse(&self, normal: Vec3) -> f32 { + self.intensity * self.radius_rad * self.radius_rad * DIFFUSE_SHARE * normal.dot(self.unit_direction()).max(0.0) + } +} + +/// Smooth 0..=1 ramp of `t` (clamped), flat at both ends +pub fn smoothstep(t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 9ed4f73b..d0067411 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,6 +1,6 @@ //! Shelf and brush preview caches //! Small synchronous renders are limited per frame -//! Smart masks and hover previews use [`PreviewWorker`] +//! Smart masks, smart materials and hover previews use [`PreviewWorker`] use std::collections::{HashMap, VecDeque}; @@ -16,7 +16,7 @@ use crate::preview_worker::PreviewWorker; use crate::shelf_preview::ShelfPreview; use crate::worker_preview::WorkerPreview; -/// Shelf thumbnails rendered per frame at most (the rest follow on the next frames) +/// UI-thread renders per frame at most; a web worker request uses the whole budget const PER_FRAME: usize = 2; /// Shelf sphere and smart mask thumbnail size in pixels const SPHERE_PX: usize = 72; @@ -37,7 +37,7 @@ pub struct Thumbs { images: HashMap, /// (frame, thumbnails rendered in it) budget: (u64, usize), - /// Renders the smart mask thumbnails and the big previews + /// Renders the orb thumbnails and the big previews worker: PreviewWorker, /// Worker-rendered previews by [`worker_key`] rendered: HashMap, @@ -82,25 +82,34 @@ impl Thumbs { /// Render within the frame budget; deferred thumbnails request a repaint fn shelf(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { let key = preview.key(); - if let Some(t) = self.shelf.get(&key) { - return Some(t.clone()); + if let Some(texture) = self.shelf.get(&key) { + return Some(texture.clone()); } + if !self.spend_budget(ctx, 1) { + return None; + } + + // An unknown asset shows as an empty thumbnail + let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT)); + let texture = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); + self.shelf.insert(key, texture.clone()); + Some(texture) + } + + /// Spend `renders` of this frame's UI-thread budget; when it is spent, request a repaint + fn spend_budget(&mut self, ctx: &egui::Context, renders: usize) -> bool { let frame = ctx.cumulative_pass_nr(); if self.budget.0 != frame { self.budget = (frame, 0); } - if self.budget.1 >= PER_FRAME { + if self.budget.1 + renders > PER_FRAME { ctx.request_repaint(); - return None; + return false; } - self.budget.1 += 1; - // An unknown asset shows as an empty thumbnail - let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT)); - let t = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); - self.shelf.insert(key, t.clone()); - Some(t) + self.budget.1 += renders; + true } /// Request once per asset and size; return None while pending or after failure @@ -109,13 +118,19 @@ impl Thumbs { self.receive(ctx); let key = worker_key(&preview, size_px); - if !self.rendered.contains_key(&key) { + if !self.rendered.contains_key(&key) && self.may_request(ctx) { let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover }); self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed }); } + self.ready(&key) } + /// Native workers take every request; the web renders inline, so it takes one per frame + fn may_request(&mut self, ctx: &egui::Context) -> bool { + !cfg!(target_arch = "wasm32") || self.spend_budget(ctx, PER_FRAME) + } + /// The worker-rendered preview under `key` if it arrived fn ready(&self, key: &str) -> Option { match self.rendered.get(key) { @@ -169,9 +184,12 @@ impl Thumbs { self.ready(&worker_key(preview, size_px)) } - /// Sphere thumbnail of built-in material `id` + /// Material thumbnail: smart materials come from the worker's orb, plain ones are spheres pub fn material(&mut self, ctx: &egui::Context, id: &'static str) -> Option { - self.shelf(ctx, ShelfPreview::Material(id), SPHERE_PX) + match ShelfPreview::material(id) { + preview @ ShelfPreview::SmartMaterial(_) => self.worker_rendered(ctx, preview, SPHERE_PX, false), + preview => self.shelf(ctx, preview, SPHERE_PX), + } } /// Smart mask thumbnail; None until the worker returns it diff --git a/crates/ui-egui/src/worker_preview.rs b/crates/ui-egui/src/worker_preview.rs index 53767276..27c3525b 100644 --- a/crates/ui-egui/src/worker_preview.rs +++ b/crates/ui-egui/src/worker_preview.rs @@ -7,6 +7,6 @@ pub enum WorkerPreview { /// Requested; the worker has not answered yet Rendering, Ready(TextureHandle), - /// The asset is unknown or the worker could not render it (the tile keeps its placeholder) + /// The asset is unknown or the worker could not render it (the tile keeps its loading icon) Failed, } diff --git a/crates/ui-egui/tests/shelf_hover_preview.rs b/crates/ui-egui/tests/shelf_hover_preview.rs index 460ed7c8..2ad76a68 100644 --- a/crates/ui-egui/tests/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/shelf_hover_preview.rs @@ -145,7 +145,7 @@ fn scrolling_with_a_stationary_pointer_defers_the_big_preview() { #[test] fn high_dpi_smart_mask_hover_stays_within_the_renderer_limit() { - use texturecraft_engine::mask_preview::MAX_PREVIEW_SIZE_PX; + use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; use texturecraft_engine::smart_masks::SMART_MASKS; let (mut harness, _) = materials_shelf(1.0 / 4.0, 3.0); From 14f2332a695704b05e7c876c13b62c787ee8e7f9 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:50:02 +0100 Subject: [PATCH 23/73] Copy the shared house rules into AGENTS.md. The blocks come from craft-contrib at dde09ea31e2e457f5b4653a6e76f7cdf55944bdf. CLAUDE.md imports AGENTS.md. The house-rules workflow checks the copy. --- .github/workflows/house-rules.yml | 28 ++++++++++++++ AGENTS.md | 64 +++++++++++++++++++++++++++---- CLAUDE.md | 6 +-- 3 files changed, 86 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/house-rules.yml diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 00000000..de64ad3e --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/AGENTS.md b/AGENTS.md index 5882a81c..c9b40de3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,56 @@ + +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. + + +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. + + # AGENTS.md: guide for AI agents and contributors TextureCraft is an open-source, native 3D texture painter: a clean-room implementation of the @@ -10,10 +63,7 @@ PdfCraft, EffectCraft, DesignCraft) in user-facing text: UI, window titles, Abou release names, docs prose. Machine names stay lowercase: crates (`texturecraft-*`), binaries, file names, ids (`ai.storyteller.texturecraft`), the native project extension `.tcraft`. -Standards and learnings shared across the crafting apps live in `../craftrules` (checked out next -to this repo, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its -standards, and contribute reusable learnings back there. Shared code goes only in craft-libs -(`standards/shared-libraries.md`); otherwise copy, don't depend. +Shared code goes only in craft-libs; otherwise copy, don't depend. The goal is 1:1 parity with Substance 3D Painter's workflow (same panels, menus, shortcuts, layer stack semantics and export conventions) with better performance, every feature drivable by agents, @@ -98,7 +148,7 @@ as a clean-room implementation, in code, docs and commits. People trust TextureCraft with hours of painting. A malformed mesh or project, a bad command or MCP param, an odd keystroke or a full disk must produce an error the user or agent can act on, never a -panic. The shared standard is `../craftrules/standards/never-crash.md`. +panic. - Non-test code never panics: no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or `unimplemented!`. Every production crate root carries @@ -176,6 +226,6 @@ after every arc of work that builds and passes. - `ROADMAP.md`: milestones, parity estimate and remaining effort. - `docs/parity.md`: generated Painter menu coverage. -- `docs/releasing.md` and `../craftrules/release/playbook.md`: release builds and signing. -- `plan/` (local, gitignored): execution plan and notes. +- `docs/releasing.md`: release builds and signing. +- `plan/` is an optional gitignored notebook (execution notes). Do not ask for it and do not stop when it is absent. - `log/` (local, gitignored): the dev log. diff --git a/CLAUDE.md b/CLAUDE.md index 3e690427..43c994c2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,5 +1 @@ -# TextureCraft: instructions for Claude - -Read [`AGENTS.md`](AGENTS.md) first: it is the guide for every agent working in this repository -(workspace map, golden rules including the asset and attribution rules, the definition of done). -Then read `../craftrules/AGENTS.md` for the standards shared by all Crafting Apps. +@AGENTS.md From 5da1f689fc2fc301f10175bc346b69a4f81bf712 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:41:09 +0100 Subject: [PATCH 24/73] docs: route release version bumps through pull requests --- docs/releasing.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/docs/releasing.md b/docs/releasing.md index c387a5f3..2658af20 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,20 +1,19 @@ # Releasing TextureCraft -The recipe is craftrules' [release playbook](release-playbook.md); this page covers what is +The recipe is the [release playbook](release-playbook.md); this page covers what is specific to TextureCraft. The pipeline is [`.github/workflows/release.yml`](../.github/workflows/release.yml). ## Release manager checklist The steps below are the release manager's; agents never create the `release` branch, tags or -GitHub Releases. The shared runbook with copy-paste `gh` commands is craftrules -`release/cut-a-release.md`. +GitHub Releases. Follow the checklist below and the linked release playbook. ### 1. One-time repository setup (org admin) Status on 2026-10-23: `storytold/texturecraft` has the `release` environment (deployable from `release` only) and the `release` ruleset (steps 1 and 2 below). Still to do before the first run: the secrets (step 3) and the runner group (step 4); the `release` branch is created by the first -release push. An org admin runs craftrules `release/signing-setup.md` steps 1-2 for this repo: +release push. An org admin completes the following setup for this repo: 1. Create the **`release` environment**, with deployment branches limited to `release`. 2. Add the **ruleset on `refs/heads/release`** (restrict creations, updates and deletions, block @@ -38,15 +37,21 @@ release push. An org admin runs craftrules `release/signing-setup.md` steps 1-2 ### 2. Set the version -On `main`: +Start from an up-to-date `main` and create a version-bump branch: ```sh +git switch main +git pull --ff-only +git switch -c bump-version-0.2.0 cargo xtask version # prints the current version cargo xtask version set 0.2.0 # or 0.2.0-rc.1 for a pre-release ``` `set` rewrites `[workspace.package] version` in the root `Cargo.toml` (the single source of truth) -and refreshes `Cargo.lock`. Commit, push, and wait for CI on `main` to pass. +and refreshes `Cargo.lock`. Commit the version bump on that branch, push the branch, and open +a pull request into `main`. Wait for the applicable checks to pass and for review, then merge +the pull request. Do not push changes directly to `main`. Wait for CI on the merged `main` +commit to pass before cutting the release below. ### 3. Cut the release @@ -160,7 +165,7 @@ unsigned artifact and a `::warning::`, never a failed build. ## Icons `assets/app-icon/texturecraft.svg` is the engraved zebra (the owner's original drawing, vectorised -to three colours, craftrules `standards/icon-design.md`); `texturecraft-small.svg` is a lighter +to three colours); `texturecraft-small.svg` is a lighter trace for the hicolor scalable icon. `packaging/icons.sh` renders everything else with resvg and `cargo xtask ico|icns`: the hicolor PNGs (16-512 px) and scalable SVG, `texturecraft-1024.png`, `texturecraft.ico` and `texturecraft.icns`. The outputs are committed; rerun it after changing the From 0f0047ae7b4f3427b7278a7cb28fac560aa0601b Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 23:27:43 +0000 Subject: [PATCH 25/73] Panel layouts survive a restart The UI state was saved as RON through eframe's storage, and a dock read through a JSON value lost RON's enum variant names, so every saved layout loaded as the default. The UI state is now saved as JSON in a store of its own: ui.json beside eframe's settings on the desktop, a storage key on the web. A saved state this build cannot fully read is kept beside it before the next save, and the state earlier builds saved still loads. --- apps/texturecraft/src/main.rs | 60 +++-- crates/ui-egui/src/lib.rs | 21 +- crates/ui-egui/src/state.rs | 24 +- crates/ui-egui/src/ui_state_store.rs | 314 ++++++++++++++++++++++++++ crates/ui-egui/tests/split_divider.rs | 14 +- 5 files changed, 373 insertions(+), 60 deletions(-) create mode 100644 crates/ui-egui/src/ui_state_store.rs diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 377b2e52..694e8826 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -11,6 +11,7 @@ mod window_frame; use texturecraft_engine::Session; use texturecraft_ui_egui::titlebar::TitleBar; +use texturecraft_ui_egui::ui_state_store; use texturecraft_ui_egui::{TextureCraftApp, UiState}; /// The app name eframe keeps the settings under (`eframe::storage_dir`). @@ -115,13 +116,16 @@ fn set_taskbar_icon(w: &winit::window::Window) { } } -/// Settings › Interface › System title bar, read from the saved settings before the window opens -/// (eframe hands the app its storage only afterwards). Missing or unreadable: off. -fn saved_system_title_bar(persistence_path: Option<&std::path::Path>) -> bool { - let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|d| d.join("app.ron"))); - let saved = file.and_then(|f| std::fs::read_to_string(f).ok()); - let kv = saved.and_then(|s| ron::from_str::>(&s).ok()); - kv.and_then(|kv| ron::from_str::(kv.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) +/// Settings › Interface › System title bar, read before the window opens from `ui.json`, else as earlier builds saved it; missing or unreadable: off +fn saved_system_title_bar(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> bool { + if let Some(ui) = ui_file.and_then(ui_state_store::read) { + return ui.prefs.system_title_bar; + } + + let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron"))); + let saved = file.and_then(|file| std::fs::read_to_string(file).ok()); + let entries = saved.and_then(|text| ron::from_str::>(&text).ok()); + entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) } /// The app with the window chrome that needs the native window: the Windows borderless guard, and @@ -170,20 +174,24 @@ fn main() { std::process::exit(2); } }; - // Errors before the window opens speak the system's language; the app then applies the saved one. + // Errors before the window opens speak the system's language; the app then applies the saved one texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language()); let prev = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { - // A message box needs the main thread on macOS; other threads' panics are only logged. + // A message box needs the main thread on macOS; other threads' panics are only logged fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main")); prev(info); })); let session = initial_session(&args); - // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS so they neither read nor - // overwrite the user's saved UI layout and settings: state goes to a throwaway folder. + // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files let persistence_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); - let title_bar = TitleBar::decide(saved_system_title_bar(persistence_path.as_deref())); + let ui_file = + persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json"))); + if let Some(file) = &ui_file { + let _ = ui_state_store::FILE.set(file.clone()); + } + let title_bar = TitleBar::decide(saved_system_title_bar(ui_file.as_deref(), persistence_path.as_deref())); let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]); if let Some(i) = icon() { viewport = viewport.with_icon(i); @@ -195,7 +203,7 @@ fn main() { std::process::exit(2); } let control = args.control; - // The start window offers new, open and recent projects, unless a file was given or a script drives the app. + // The start window offers new, open and recent projects, unless a file was given or a script drives the app let start = args.file.is_none() && control.is_none(); let r = eframe::run_native( APP_NAME, @@ -296,19 +304,27 @@ mod tests { } #[test] - fn the_system_title_bar_setting_is_read_from_eframes_settings_file() { - let path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); + fn the_system_title_bar_setting_is_read_from_ui_json_else_as_earlier_builds_saved_it() { + let ron_path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); + let json_path = ron_path.with_extension("json"); for on in [false, true] { let mut ui = UiState::default(); ui.prefs.system_title_bar = on; - // Written as eframe writes it: a pretty RON map of RON strings. + // Written as eframe writes it: a pretty RON map of RON strings let kv = std::collections::HashMap::from([("ui".to_string(), ron::to_string(&ui).unwrap())]); - std::fs::write(&path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); - assert_eq!(saved_system_title_bar(Some(&path)), on); + std::fs::write(&ron_path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); + assert_eq!(saved_system_title_bar(None, Some(&ron_path)), on); + + ui.prefs.system_title_bar = !on; + std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap(); + assert_eq!(saved_system_title_bar(Some(&json_path), Some(&ron_path)), !on, "ui.json comes first"); } - std::fs::write(&path, "not ron").unwrap(); - assert!(!saved_system_title_bar(Some(&path))); - std::fs::remove_file(&path).unwrap(); - assert!(!saved_system_title_bar(Some(&path))); + + std::fs::write(&json_path, "not json").unwrap(); + std::fs::write(&ron_path, "not ron").unwrap(); + assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); + std::fs::remove_file(&json_path).unwrap(); + std::fs::remove_file(&ron_path).unwrap(); + assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 375ff1ba..2a586519 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -32,6 +32,7 @@ pub mod theme; pub mod thumbs; pub mod titlebar; pub mod toolbar; +pub mod ui_state_store; pub mod viewport; pub mod web_files; pub mod widgets; @@ -85,6 +86,8 @@ pub struct TextureCraftApp { /// A smooth move to a saved camera in progress. camera_glide: Option, pub ui: UiState, + /// Where `ui` is saved between runs + ui_store: ui_state_store::UiStateStore, pub gpu: Option, pub control: Option>, pub toasts: Vec, @@ -132,12 +135,13 @@ pub struct TextureCraftApp { impl TextureCraftApp { pub fn new(cc: &eframe::CreationContext<'_>, session: Session) -> TextureCraftApp { theme::install(&cc.egui_ctx); - // Bakes cast their rays on a GPU device of their own (created on the first bake). + // Bakes cast their rays on a GPU device of their own (created on the first bake) #[cfg(not(target_arch = "wasm32"))] texturecraft_engine::bake::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); - let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx)); - // The first run speaks the OS (or browser) language. - let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_else(|| { + let gpu = cc.wgpu_render_state.as_ref().map(|render_state| gpu::init(render_state, &cc.egui_ctx)); + // The first run speaks the OS (or browser) language + let mut ui_store = ui_state_store::UiStateStore::new(ui_state_store::FILE.get().cloned()); + let ui = ui_store.load(cc.storage).unwrap_or_else(|| { let mut ui = UiState::default(); ui.prefs.language = i18n::os_language().into(); ui @@ -147,6 +151,7 @@ impl TextureCraftApp { camera_glide: None, session, ui, + ui_store, gpu, control: None, toasts: Vec::new(), @@ -179,14 +184,14 @@ impl TextureCraftApp { export_templates::load_library(&mut app, cc.storage); #[cfg(not(target_arch = "wasm32"))] { - // The first window of the process fixes it; a new folder applies on restart. + // The first window of the process fixes it; a new folder applies on restart let _ = DATA_FOLDER.set(data_folder(&app.ui.prefs.data_folder)); - // An export folder still at the default follows the data folder. + // An export folder still at the default follows the data folder if app.ui.export.dir == data_folder("").join("export").display().to_string() { app.ui.export.dir = user_dir("export").display().to_string(); } let skipped = app.session.load_templates(user_dir("templates")); - app.session.log.extend(skipped.into_iter().map(|w| format!("Project template skipped: {w}"))); + app.session.log.extend(skipped.into_iter().map(|warning| format!("Project template skipped: {warning}"))); } app } @@ -477,7 +482,7 @@ impl eframe::App for TextureCraftApp { } fn save(&mut self, storage: &mut dyn eframe::Storage) { - eframe::set_value(storage, "ui", &self.ui); + self.ui_store.save(&self.ui, storage); export_templates::save_library(self, storage); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..2aaab049 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -429,35 +429,13 @@ mod tests { } } - /// The app's own settings store: eframe keeps `UiState` as RON text under a key - #[derive(Default)] - struct MemoryStorage(std::collections::HashMap); - - impl eframe::Storage for MemoryStorage { - fn get_string(&self, key: &str) -> Option { - self.0.get(key).cloned() - } - - fn set_string(&mut self, key: &str, value: String) { - self.0.insert(key.to_string(), value); - } - - fn remove_string(&mut self, key: &str) { - self.0.remove(key); - } - - fn flush(&mut self) {} - } - #[test] fn the_bake_layout_survives_a_restart_whichever_mode_was_open() { for mode in [Mode::Painting, Mode::Baking] { let mut ui = UiState { mode, ..UiState::default() }; ui.sync_mode_dock(); - let mut storage = MemoryStorage::default(); - eframe::set_value(&mut storage, "ui", &ui); - let mut restarted: UiState = eframe::get_value(&storage, "ui").unwrap(); + let mut restarted = crate::ui_state_store::tests::restart(&ui); restarted.sync_mode_dock(); let bake_dock = if mode == Mode::Baking { &restarted.dock } else { &restarted.inactive_mode_dock }; assert_eq!(*bake_dock, Dock::for_baking(), "{mode:?}"); diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs new file mode 100644 index 00000000..467dad78 --- /dev/null +++ b/crates/ui-egui/src/ui_state_store.rs @@ -0,0 +1,314 @@ +//! The UI state kept between runs as JSON: `ui.json` beside eframe's settings on the desktop, a key of eframe's storage on the web + +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +use crate::UiState; + +/// eframe storage key of the UI state as JSON, where there is no file +const STORAGE_KEY: &str = "ui.json"; + +/// eframe storage key under which earlier builds kept the UI state, as RON +const RON_STORAGE_KEY: &str = "ui"; + +/// eframe storage key of a saved state this build could not fully read, where there is no file +const UNREADABLE_STORAGE_KEY: &str = "ui.unreadable.json"; + +/// Largest UI state file read; a saved state is a few kilobytes +const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; + +/// Copies of unreadable saved states kept beside the file before saving stops +const MAX_UNREADABLE_COPIES: u32 = 10; + +/// The desktop's `ui.json`, set by the app before its window opens; unset, the state stays in eframe's storage +pub static FILE: OnceLock = OnceLock::new(); + +/// Where the UI state is saved, holding a saved state this build could not fully read until it is kept beside it +#[derive(Default)] +pub struct UiStateStore { + file: Option, + unreadable: Option>, + /// The unreadable state could not be kept, so the saved one is left as it is + frozen: bool, +} + +impl UiStateStore { + /// The store at `file`, or in eframe's storage without one + pub fn new(file: Option) -> Self { + UiStateStore { file, unreadable: None, frozen: false } + } + + /// The saved UI state, else the one an earlier build saved; a state not fully read is kept for the next save + pub fn load(&mut self, storage: Option<&dyn eframe::Storage>) -> Option { + let saved = match &self.file { + Some(file) if too_large(file) => { + self.frozen = true; + return None; + } + Some(file) => std::fs::read(file).ok(), + None => storage.and_then(|storage| storage.get_string(STORAGE_KEY)).map(String::into_bytes), + }; + let Some(bytes) = saved else { + return storage.and_then(|storage| eframe::get_value::(storage, RON_STORAGE_KEY)); + }; + + let ui = serde_json::from_slice::(&bytes).ok(); + if !ui.as_ref().is_some_and(fully_read) { + self.unreadable = Some(bytes); + } + ui + } + + /// Save `ui` as JSON once an unreadable saved state is kept, and drop the RON copy of earlier builds + pub fn save(&mut self, ui: &UiState, storage: &mut dyn eframe::Storage) { + if let Some(bytes) = self.unreadable.take() { + self.frozen = !self.keep_unreadable(&bytes, storage); + } + if self.frozen { + return; + } + + let Ok(json) = serde_json::to_string_pretty(ui) else { return }; + let saved = match &self.file { + Some(file) => write_file(file, json.as_bytes()), + None => { + storage.set_string(STORAGE_KEY, json); + true + } + }; + if saved { + storage.remove_string(RON_STORAGE_KEY); + } + } + + /// Keep a saved state this build could not fully read, beside the file or under its own storage key + fn keep_unreadable(&self, bytes: &[u8], storage: &mut dyn eframe::Storage) -> bool { + match &self.file { + Some(file) => keep_file_copy(file, bytes), + None => { + storage.set_string(UNREADABLE_STORAGE_KEY, String::from_utf8_lossy(bytes).into_owned()); + true + } + } + } +} + +/// The UI state saved in `file`, if it reads +pub fn read(file: &Path) -> Option { + if too_large(file) { + return None; + } + + serde_json::from_slice(&std::fs::read(file).ok()?).ok() +} + +/// Whether both docks were read rather than replaced by a default +fn fully_read(ui: &UiState) -> bool { + !ui.dock.replaced_unreadable() && !ui.inactive_mode_dock.replaced_unreadable() +} + +/// Whether `file` is too large to be a saved UI state, so it is neither read nor saved over +fn too_large(file: &Path) -> bool { + std::fs::metadata(file).is_ok_and(|metadata| metadata.len() > MAX_FILE_BYTES) +} + +#[cfg(not(target_arch = "wasm32"))] +fn write_file(file: &Path, bytes: &[u8]) -> bool { + if let Some(folder) = file.parent() { + let _ = std::fs::create_dir_all(folder); + } + + texturecraft_engine::formats::write_atomic(file, bytes).is_ok() +} + +#[cfg(target_arch = "wasm32")] +fn write_file(_file: &Path, _bytes: &[u8]) -> bool { + false +} + +/// Copy `bytes` beside `file` as the first free `.unreadable.json` or `.unreadable-N.json` +fn keep_file_copy(file: &Path, bytes: &[u8]) -> bool { + use std::io::Write as _; + + let stem = file.file_stem().map(|stem| stem.to_string_lossy().into_owned()).unwrap_or_default(); + for n in 1..=MAX_UNREADABLE_COPIES { + let name = if n == 1 { format!("{stem}.unreadable.json") } else { format!("{stem}.unreadable-{n}.json") }; + match std::fs::OpenOptions::new().write(true).create_new(true).open(file.with_file_name(name)) { + Ok(mut copy) => return copy.write_all(bytes).is_ok(), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(_) => return false, + } + } + false +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::docking::{Dock, Panel, default_workspace, permissions}; + use craft_ui::docking::{Action, Placement}; + + /// eframe's storage held in memory + #[derive(Default)] + pub(crate) struct MemoryStorage(pub(crate) std::collections::HashMap); + + impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.0.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + self.0.insert(key.to_owned(), value); + } + + fn remove_string(&mut self, key: &str) { + self.0.remove(key); + } + + fn flush(&mut self) {} + } + + /// Save `ui` and load it back, as closing and reopening the app does + pub(crate) fn restart(ui: &UiState) -> UiState { + let mut storage = MemoryStorage::default(); + UiStateStore::default().save(ui, &mut storage); + UiStateStore::default().load(Some(&storage)).unwrap_or_else(|| panic!("the saved state loads: {:?}", storage.0)) + } + + /// An empty folder of its own for one test + fn test_folder(name: &str) -> PathBuf { + let folder = std::env::temp_dir().join(format!("texturecraft-ui-store-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + folder + } + + /// The painting default with Layers moved into a tab beside Assets and Properties floating + fn moved_panels() -> Dock { + let mut workspace = default_workspace(); + let actions = [ + Action::Move { panel: Panel::Layers, anchor: Panel::Assets, placement: Placement::Tab { before: None } }, + Action::Float { panel: Panel::Properties, rect: [900.0, 120.0, 320.0, 400.0] }, + ]; + workspace.apply_all(actions, permissions).unwrap(); + + let dock = Dock::from_value(serde_json::to_value(&workspace).unwrap()); + assert!(!dock.replaced_unreadable(), "the moved layout is valid"); + dock + } + + #[test] + fn panel_layouts_survive_a_restart_in_the_file_and_in_storage() { + let folder = test_folder("layouts"); + for dock in [Dock::default(), moved_panels()] { + let ui = UiState { dock, split_ratio: 0.3, ..UiState::default() }; + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + UiStateStore::new(file.clone()).save(&ui, &mut storage); + + let restarted = UiStateStore::new(file.clone()).load(Some(&storage)).unwrap(); + assert!(fully_read(&restarted), "{file:?}"); + assert_eq!(restarted, ui, "{file:?}"); + } + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn the_state_an_earlier_build_saved_loads_and_its_copy_goes_on_the_next_save() { + let mut storage = MemoryStorage::default(); + let earlier = UiState { split_ratio: 0.3, ..UiState::default() }; + eframe::set_value(&mut storage, RON_STORAGE_KEY, &earlier); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).expect("the earlier state loads"); + assert_eq!(loaded.split_ratio, 0.3); + + store.save(&loaded, &mut storage); + assert!(!storage.0.contains_key(RON_STORAGE_KEY)); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } + + #[test] + fn an_unreadable_layout_loads_the_default_and_is_kept_beside_the_file() { + let folder = test_folder("unreadable"); + let file = folder.join("ui.json"); + let ui = UiState { dock: moved_panels(), split_ratio: 0.3, ..UiState::default() }; + let mut storage = MemoryStorage::default(); + UiStateStore::new(Some(file.clone())).save(&ui, &mut storage); + let saved = std::fs::read_to_string(&file).unwrap(); + assert!(saved.contains("\"Assets\"") && saved.contains("\"version\": 2"), "{saved}"); + + let unreadable = [ + // A panel this build does not know + saved.replacen("\"Assets\"", "\"Bogus\"", 1), + // A layout from a newer format + saved.replacen("\"version\": 2", "\"version\": 99", 1), + // Not a saved state + "not json".to_owned(), + ]; + for (n, text) in unreadable.iter().enumerate() { + std::fs::write(&file, text).unwrap(); + let mut store = UiStateStore::new(Some(file.clone())); + let loaded = store.load(Some(&storage)); + if let Some(loaded) = &loaded { + assert_eq!(loaded.dock, Dock::default(), "{text}"); + assert_eq!(loaded.split_ratio, 0.3, "{text}"); + } + + store.save(&loaded.unwrap_or_default(), &mut storage); + let copy = if n == 0 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{}.json", n + 1) }; + assert_eq!(std::fs::read_to_string(folder.join(copy)).unwrap(), *text); + assert_ne!(std::fs::read_to_string(&file).unwrap(), *text, "the next save replaces it once kept"); + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn an_unreadable_state_that_cannot_be_kept_is_not_saved_over() { + let folder = test_folder("frozen"); + let file = folder.join("ui.json"); + for n in 1..=MAX_UNREADABLE_COPIES { + let name = if n == 1 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{n}.json") }; + std::fs::write(folder.join(name), "").unwrap(); + } + std::fs::write(&file, "not json").unwrap(); + + let mut store = UiStateStore::new(Some(file.clone())); + let mut storage = MemoryStorage::default(); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + store.save(&UiState::default(), &mut storage); + assert_eq!(std::fs::read_to_string(&file).unwrap(), "not json"); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_file_too_large_to_read_is_not_saved_over() { + let folder = test_folder("too-large"); + let file = folder.join("ui.json"); + std::fs::write(&file, vec![b' '; MAX_FILE_BYTES as usize + 1]).unwrap(); + + let mut store = UiStateStore::new(Some(file.clone())); + let mut storage = MemoryStorage::default(); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + assert_eq!(std::fs::metadata(&file).unwrap().len(), MAX_FILE_BYTES + 1); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn an_unreadable_layout_in_storage_is_kept_under_its_own_key() { + let mut storage = MemoryStorage::default(); + UiStateStore::default().save(&UiState { dock: moved_panels(), ..UiState::default() }, &mut storage); + let bogus = storage.0[STORAGE_KEY].replacen("\"Assets\"", "\"Bogus\"", 1); + storage.0.insert(STORAGE_KEY.to_owned(), bogus.clone()); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).unwrap(); + assert_eq!(loaded.dock, Dock::default()); + store.save(&loaded, &mut storage); + assert_eq!(storage.0[UNREADABLE_STORAGE_KEY], bogus); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } +} diff --git a/crates/ui-egui/tests/split_divider.rs b/crates/ui-egui/tests/split_divider.rs index d5af8c8f..e0a487fc 100644 --- a/crates/ui-egui/tests/split_divider.rs +++ b/crates/ui-egui/tests/split_divider.rs @@ -5,6 +5,7 @@ use egui_kittest::Harness; use texturecraft_engine::core::Channel; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::UiState; +use texturecraft_ui_egui::ui_state_store::UiStateStore; /// Narrowest a split view may get, as in `viewport.rs` const MIN_VIEW_WIDTH: f32 = 16.0; @@ -144,16 +145,15 @@ fn the_divider_position_survives_a_restart_and_old_saved_states_load_centred() { let mut storage = MemoryStorage::default(); let mut ui_state = UiState::default(); ui_state.split_ratio = 0.3; - eframe::set_value(&mut storage, "ui", &ui_state); - let restored = eframe::get_value::(&storage, "ui").expect("saved state loads"); + UiStateStore::default().save(&ui_state, &mut storage); + let restored = UiStateStore::default().load(Some(&storage)).expect("saved state loads"); assert_eq!(restored.split_ratio, 0.3); // A state saved before the divider existed has no ratio - let saved = storage.0.get("ui").cloned().unwrap(); - let without_ratio = saved.replace("split_ratio:0.3,", ""); - assert_ne!(without_ratio, saved, "the saved state names the ratio: {saved}"); - storage.0.insert("ui".to_owned(), without_ratio); - let restored = eframe::get_value::(&storage, "ui").expect("an older saved state loads"); + let mut saved: serde_json::Value = serde_json::from_str(&storage.0["ui.json"]).unwrap(); + assert!(saved.as_object_mut().unwrap().remove("split_ratio").is_some(), "the saved state names the ratio: {saved}"); + storage.0.insert("ui.json".to_owned(), saved.to_string()); + let restored = UiStateStore::default().load(Some(&storage)).expect("an older saved state loads"); assert_eq!(restored.split_ratio, 0.5); } From b1f377b8eb76705aeea098f048b7e0a78730e15f Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 23:46:46 +0000 Subject: [PATCH 26/73] Bake curvature from the mesh by default The normal-map method cannot see the low poly's own edges: a box baked from itself gets flat curvature, and a box baked from a beveled high poly gets a dark line along its convex edges. New projects now start on the mesh method; projects that store a method keep it. --- crates/bake/src/tests.rs | 19 ++++++++++++++ crates/core/src/bake/curvature_method.rs | 2 +- crates/core/src/bake/curvature_settings.rs | 8 +----- crates/core/tests/bake_settings.rs | 4 ++- crates/ui-egui/tests/bake_mode.rs | 29 ++++++++++++++-------- 5 files changed, 43 insertions(+), 19 deletions(-) diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index bb75353e..aaa855f6 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -565,6 +565,25 @@ fn a_high_poly_box_has_bright_edges_and_flat_faces() { } } +#[test] +fn default_curvature_brightens_box_edges_and_never_darkens_them() { + let mut bake_settings = settings(256, &[BakedMap::Curvature]); + bake_settings.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..bake_settings.cage }; + bake_settings.maps.curvature.parameters.method = CurvatureMethod::default(); + + // A box has no concave texel, whether it is baked from itself or from a beveled high poly + let low = primitives::cube(2.0); + let high = primitives::rounded_box(Vec3::ONE, 0.15); + let bakes = [("itself", run(&low, &bake_settings).unwrap()), ("a beveled high poly", transfer(&low, &high, None, &bake_settings).unwrap())]; + for (source, bake_output) in bakes { + let curvature = covered_values(&low, &bake_output, BakedMap::Curvature); + let darkest = curvature.iter().map(|(_, value)| *value).fold(1.0, f32::min); + let brightest = curvature.iter().map(|(_, value)| *value).fold(0.0, f32::max); + assert!(darkest > 0.45, "baked from {source}, darkest {darkest}"); + assert!(brightest > 0.6, "baked from {source}, brightest {brightest}"); + } +} + #[test] fn a_narrow_high_poly_bevel_stays_bright() { let s = { diff --git a/crates/core/src/bake/curvature_method.rs b/crates/core/src/bake/curvature_method.rs index 2085c85b..32ac645b 100644 --- a/crates/core/src/bake/curvature_method.rs +++ b/crates/core/src/bake/curvature_method.rs @@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum CurvatureMethod { - #[default] NormalMap, + #[default] Mesh, } diff --git a/crates/core/src/bake/curvature_settings.rs b/crates/core/src/bake/curvature_settings.rs index d67138b8..66b4e732 100644 --- a/crates/core/src/bake/curvature_settings.rs +++ b/crates/core/src/bake/curvature_settings.rs @@ -1,16 +1,10 @@ use super::{CurvatureMethod, MeshCurvatureSettings, NormalMapCurvatureSettings}; use serde::{Deserialize, Serialize}; -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct CurvatureSettings { pub method: CurvatureMethod, pub normal_map: NormalMapCurvatureSettings, pub mesh: MeshCurvatureSettings, } - -impl Default for CurvatureSettings { - fn default() -> Self { - Self { method: CurvatureMethod::NormalMap, normal_map: NormalMapCurvatureSettings::default(), mesh: MeshCurvatureSettings::default() } - } -} diff --git a/crates/core/tests/bake_settings.rs b/crates/core/tests/bake_settings.rs index 708560f0..800efd98 100644 --- a/crates/core/tests/bake_settings.rs +++ b/crates/core/tests/bake_settings.rs @@ -20,7 +20,7 @@ fn reference_defaults_cover_common_and_per_map_settings() { "id": {"source": "MaterialColor", "generator": "HueShift"}, "ao": {"rays": rays, "ignore_backface": "Never", "self_occlusion": "Always", "attenuation": "Linear", "ground_plane": {"enabled": false, "offset": 0.0}}, "curvature": { - "method": "NormalMap", + "method": "Mesh", "normal_map": {"details": 0.5, "enable_seams": true, "seams_intensity": 1.0}, "mesh": {"rays": 32, "sampling_radius": 0.001, "relative_to_bounding_box": true, "self_intersection": "Always", "auto_tonemapping": true, "value_min": -1.0, "value_max": 1.0} }, @@ -54,7 +54,9 @@ fn reference_defaults_cover_common_and_per_map_settings() { } } } + assert_shape(&serde_json::to_value(decoded).unwrap(), &expected); + assert_eq!(BakedMap::ALL.len(), 10); for name in ["color_map", "Color map", "WorldDirection", "world_space_direction"] { assert_eq!(BakedMap::parse(name), None); diff --git a/crates/ui-egui/tests/bake_mode.rs b/crates/ui-egui/tests/bake_mode.rs index 88a7c1f2..1b330244 100644 --- a/crates/ui-egui/tests/bake_mode.rs +++ b/crates/ui-egui/tests/bake_mode.rs @@ -434,39 +434,48 @@ fn check_all_enables_every_map_then_disables_them_all() { #[test] fn the_breadcrumb_switches_the_shown_map() { let mut harness = harness(Some(BakedMap::Curvature)); - harness.get_by_label("Details"); + harness.get_by_label("Sampling Radius"); assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 1, "only the list row before the menu opens"); + let dropdowns: Vec<_> = harness.get_all_by_label(egui_phosphor::regular::CARET_RIGHT).collect(); let [_texture_set_dropdown, map_dropdown] = dropdowns.as_slice() else { panic!("the breadcrumb has a texture set and a map dropdown") }; map_dropdown.click(); harness.run_steps(3); assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 2, "the map menu lists Position"); + // The menu draws its items after the list rows harness.get_all_by_role_and_label(Role::Button, "Position").last().unwrap().click(); harness.run_steps(3); harness.get_by_label("Normalization Scale"); - assert!(harness.query_by_label("Details").is_none()); + assert!(harness.query_by_label("Sampling Radius").is_none()); assert_eq!(enabled_maps(&harness), [BakedMap::Curvature]); } #[test] fn curvature_controls_follow_the_method_and_notes_visibility_rules() { let mut harness = harness(Some(BakedMap::Curvature)); - harness.get_by_label("Details"); - harness.get_by_label("Seams Intensity"); - click(&mut harness, "Enable Seams"); - assert!(harness.query_by_label("Seams Intensity").is_none()); - click(&mut harness, "Method"); - click(&mut harness, "Generate from Mesh"); - assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters.method, CurvatureMethod::Mesh); + let curvature = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters; + + assert_eq!(curvature(&harness).method, CurvatureMethod::Mesh); assert!(harness.query_by_label("Details").is_none()); harness.get_by_label("Sampling Radius"); assert!(harness.query_by_label("Value Bounds Min").is_none()); assert!(harness.query_by_label("Value Bounds Max").is_none()); + click(&mut harness, "Auto Tonemapping"); harness.get_by_label("Value Bounds Min"); harness.get_by_label("Value Bounds Max"); - assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters.mesh.auto_tonemapping); + assert!(!curvature(&harness).mesh.auto_tonemapping); + + click(&mut harness, "Method"); + click(&mut harness, "Generate from Normal Map"); + assert_eq!(curvature(&harness).method, CurvatureMethod::NormalMap); + assert!(harness.query_by_label("Sampling Radius").is_none()); + harness.get_by_label("Details"); + + harness.get_by_label("Seams Intensity"); + click(&mut harness, "Enable Seams"); + assert!(harness.query_by_label("Seams Intensity").is_none()); } #[test] From b0c07454af61416c860246053d3b05e373369932 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 00:05:59 +0000 Subject: [PATCH 27/73] Collapsible UV transformations section for fill projections Fill Properties keep the projection kind, its axis and the tri-planar hardness visible, and move scale, rotation and offsets into a collapsible "UV transformations" section, open by default, so the material channels sit higher. Each fill keeps its own open or closed state. The tri-planar "Blend sharpness" slider is now labelled "Hardness"; its range and effect are unchanged. --- crates/ui-egui/src/dock.rs | 108 +++++++++--------- crates/ui-egui/src/i18n/ar.rs | 2 +- crates/ui-egui/src/i18n/de.rs | 2 +- crates/ui-egui/src/i18n/es.rs | 2 +- crates/ui-egui/src/i18n/fr.rs | 2 +- crates/ui-egui/src/i18n/it.rs | 2 +- crates/ui-egui/src/i18n/ja.rs | 2 +- crates/ui-egui/src/i18n/ko.rs | 2 +- crates/ui-egui/src/i18n/pt_br.rs | 2 +- crates/ui-egui/src/i18n/zh_hans.rs | 2 +- .../ui-egui/tests/fill_projection_section.rs | 68 +++++++++++ 11 files changed, 132 insertions(+), 62 deletions(-) create mode 100644 crates/ui-egui/tests/fill_projection_section.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 4d5a1d06..702104c0 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,7 +6,7 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, - Source, + Projection, Source, }; use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; use texturecraft_engine::paint::{BrushAlpha, alphas}; @@ -1572,46 +1572,41 @@ fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> Str trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]) } -/// Projection and per-channel sources of a fill: a fill layer's (`base` = {"layer"}, `on` = -/// its enabled channels) or a content fill effect's (`base` = {"effect"}, `on` = the channels -/// it has a source for). `reader` is the layer owning the fill (for anchor sources). +/// Projection and channel sources of a fill layer (`base` = {"layer"}) or fill effect (`base` = {"effect"}) filling `on`, owned by `reader` fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, on: &[Channel], reader: LayerId) { - use texturecraft_engine::core::Projection; let salt = base.to_string(); - if let Projection::Decal(d) = &fill.projection { - decal_editor(app, ui, d, reader); + if let Projection::Decal(decal) = &fill.projection { + decal_editor(app, ui, decal, reader); } else { projection_editor(app, ui, fill, base); } + ui.add_space(6.0); ui.label(caption(tr("Material"))); - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); ui.horizontal_wrapped(|ui| { - for c in &chans { - let enabled = on.contains(c); - if chip(ui, tr(c.short()), enabled).on_hover_text(tr(SOLO_HINT)).clicked() { - let solo = ui.input(|i| i.modifiers.alt); - app.run("layer.fill.set", with(base, json!({"channel": c.id(), "enabled": solo || !enabled, "solo": solo}))); + for channel in &channels { + let enabled = on.contains(channel); + if chip(ui, tr(channel.short()), enabled).on_hover_text(tr(SOLO_HINT)).clicked() { + let solo = ui.input(|input| input.modifiers.alt); + app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "enabled": solo || !enabled, "solo": solo}))); } } }); + ui.add_space(4.0); let anchors = anchors_below(app, reader); - for c in chans { - if !on.contains(&c) { - continue; + for channel in channels { + if on.contains(&channel) { + fill_channel(app, ui, fill, base, channel, &anchors, &salt); } - fill_channel(app, ui, fill, base, c, &anchors, &salt); } } -/// The projection of a fill (other than a decal): kind, scale, and what the kind adds (UV -/// rotation and offset, tri-planar sharpness, an axis, a world offset). Each edit sends only the -/// field it changed; the command keeps the others. +/// A fill's projection kind, axis and tri-planar hardness, then its collapsible UV transformations; each edit sends only its field fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value) { - use texturecraft_engine::core::Projection; - let proj_label = fill.projection.label(); - combo(ui, tr("Projection"), tr(proj_label), |ui| { + let projection_label = fill.projection.label(); + combo(ui, tr("Projection"), tr(projection_label), |ui| { for (id, label) in [ ("uv", n_("UV projection")), ("triplanar", n_("Tri-planar projection")), @@ -1619,55 +1614,62 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: ("spherical", n_("Spherical projection")), ("cylindrical", n_("Cylindrical projection")), ] { - if ui.selectable_label(proj_label == label, tr(label)).clicked() { + if ui.selectable_label(projection_label == label, tr(label)).clicked() { app.run("layer.fill.projection", with(base, json!({"projection": id}))); } } }); - let mut scale = match &fill.projection { + + let mut edit = |extra: Value| { + app.run("layer.fill.projection", with(base, extra)); + }; + if let Projection::Planar { axis, .. } | Projection::Cylindrical { axis, .. } = &fill.projection + && let Some(picked_axis) = axis_combo(ui, *axis) + { + edit(json!({"axis": picked_axis})); + } + if let Projection::Triplanar { sharpness, .. } = &fill.projection { + let mut sharpness = *sharpness; + if let Some(merge) = slider_edit(ui, tr("Hardness"), &mut sharpness, 1.0..=64.0, 1) { + edit(json!({"sharpness": sharpness, "merge": merge})); + } + } + + // One id per fill so each keeps its own open or closed state + section(ui, &format!("sec_fill_transform{base}"), tr("UV transformations"), true, |ui| { + projection_transform(ui, &fill.projection, &mut edit); + }); +} + +/// Scale plus what the projection kind adds: UV rotation and offset, or a world offset +fn projection_transform(ui: &mut Ui, projection: &Projection, edit: &mut impl FnMut(Value)) { + let mut scale = match projection { Projection::Uv { scale, .. } => scale[0], Projection::Triplanar { scale, .. } | Projection::Planar { scale, .. } | Projection::Spherical { scale } | Projection::Cylindrical { scale, .. } => { *scale } Projection::Decal(_) => return, }; - let mut edit = |extra: Value| app.run("layer.fill.projection", with(base, extra)); if let Some(merge) = slider_edit(ui, tr("Scale / tiling"), &mut scale, 0.01..=20.0, 2) { edit(json!({"scale": scale, "merge": merge})); } - match &fill.projection { + + match projection { Projection::Uv { rotation, offset, .. } => { - let mut r = *rotation; - if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut r, 0.0..=360.0, 0) { - edit(json!({"rotation": r, "merge": merge})); + let mut rotation_degrees = *rotation; + if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut rotation_degrees, 0.0..=360.0, 0) { + edit(json!({"rotation": rotation_degrees, "merge": merge})); } - if let Some((o, merge)) = offset_sliders(ui, ["U", "V"], *offset) { - edit(json!({"offset": o, "merge": merge})); + if let Some((offset, merge)) = offset_sliders(ui, ["U", "V"], *offset) { + edit(json!({"offset": offset, "merge": merge})); } } - Projection::Triplanar { sharpness, offset, .. } => { - let mut s = *sharpness; - if let Some(merge) = slider_edit(ui, tr("Blend sharpness"), &mut s, 1.0..=64.0, 1) { - edit(json!({"sharpness": s, "merge": merge})); - } - if let Some((o, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { - edit(json!({"offset": o, "merge": merge})); + Projection::Triplanar { offset, .. } | Projection::Planar { offset, .. } => { + if let Some((offset, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { + edit(json!({"offset": offset, "merge": merge})); } } - Projection::Planar { axis, offset, .. } => { - if let Some(a) = axis_combo(ui, *axis) { - edit(json!({"axis": a})); - } - if let Some((o, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { - edit(json!({"offset": o, "merge": merge})); - } - } - Projection::Cylindrical { axis, .. } => { - if let Some(a) = axis_combo(ui, *axis) { - edit(json!({"axis": a})); - } - } - Projection::Spherical { .. } | Projection::Decal(_) => {} + Projection::Spherical { .. } | Projection::Cylindrical { .. } | Projection::Decal(_) => {} } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 0f2e023f..21c87eb2 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -105,7 +105,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "النواظم المنحنية"), ("Bevel", "شطف الحواف"), ("Black", "أسود"), - ("Blend sharpness", "حدة المزج"), ("Blending", "الدمج"), ("Blending mode of the displayed channel", "نمط الدمج للقناة المعروضة"), ("Blur", "تمويه"), @@ -796,6 +795,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ مع الخامات"), ("UV checker", "رقعة فحص UV"), ("UV island fill", "تعبئة جزيرة UV"), + ("UV transformations", "تحويلات UV"), ("UV projection", "إسقاط UV"), ("UV tiles", "بلاطات UV"), ("UV tiles (UDIM)", "بلاطات UV (UDIM)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 77cf296b..ea536d5e 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -105,7 +105,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Gebogene Normalen"), ("Bevel", "Abschrägung"), ("Black", "Schwarz"), - ("Blend sharpness", "Übergangsschärfe"), ("Blending", "Überblendung"), ("Blending mode of the displayed channel", "Füllmethode des angezeigten Kanals"), ("Blur", "Weichzeichnen"), @@ -835,6 +834,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ mit Texturen"), ("UV checker", "UV-Schachbrett"), ("UV island fill", "UV-Insel-Füllung"), + ("UV transformations", "UV-Transformationen"), ("UV projection", "UV-Projektion"), ("UV tiles", "UV-Kacheln"), ("UV tiles (UDIM)", "UV-Kacheln (UDIM)"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 4153783e..de7c76e2 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -105,7 +105,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Normales curvadas"), ("Bevel", "Bisel"), ("Black", "Negro"), - ("Blend sharpness", "Nitidez de la mezcla"), ("Blending", "Fusión"), ("Blending mode of the displayed channel", "Modo de fusión del canal mostrado"), ("Blur", "Desenfoque"), @@ -823,6 +822,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ con texturas"), ("UV checker", "Damero UV"), ("UV island fill", "Relleno de islas UV"), + ("UV transformations", "Transformaciones UV"), ("UV projection", "Proyección UV"), ("UV tiles", "Mosaicos UV"), ("UV tiles (UDIM)", "Mosaicos UV (UDIM)"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 0c07e5a4..fc4b8b11 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -111,7 +111,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Normales déviées"), ("Bevel", "Biseau"), ("Black", "Noir"), - ("Blend sharpness", "Netteté du fondu"), ("Blending", "Fusion"), ("Blending mode of the displayed channel", "Mode de fusion du canal affiché"), ("Blur", "Flou"), @@ -841,6 +840,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ avec textures"), ("UV checker", "Damier UV"), ("UV island fill", "Remplissage d'îlots UV"), + ("UV transformations", "Transformations UV"), ("UV projection", "Projection UV"), ("UV tiles", "Tuiles UV"), ("UV tiles (UDIM)", "Tuiles UV (UDIM)"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index b4bd33b3..67648219 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -108,7 +108,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Bent normal"), ("Bevel", "Smusso"), ("Black", "Nero"), - ("Blend sharpness", "Nitidezza della fusione"), ("Blending", "Fusione"), ("Blending mode of the displayed channel", "Metodo di fusione del canale visualizzato"), ("Blur", "Sfocatura"), @@ -832,6 +831,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ con texture"), ("UV checker", "Scacchiera UV"), ("UV island fill", "Riempimento isola UV"), + ("UV transformations", "Trasformazioni UV"), ("UV projection", "Proiezione UV"), ("UV tiles", "Tile UV"), ("UV tiles (UDIM)", "Tile UV (UDIM)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index f764e268..dfbe8a65 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -111,7 +111,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "ベントノーマル"), ("Bevel", "ベベル"), ("Black", "黒"), - ("Blend sharpness", "ブレンドのシャープさ"), ("Blending", "ブレンド"), ("Blending mode of the displayed channel", "表示中のチャンネルのブレンドモード"), ("Blur", "ぼかし"), @@ -814,6 +813,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ (テクスチャ付き)"), ("UV checker", "UVチェッカー"), ("UV island fill", "UVアイランド塗りつぶし"), + ("UV transformations", "UV変換"), ("UV projection", "UV投影"), ("UV tiles", "UVタイル"), ("UV tiles (UDIM)", "UVタイル (UDIM)"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index a1c8d363..f81cfe6d 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -105,7 +105,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "벤트 노멀"), ("Bevel", "베벨"), ("Black", "검은색"), - ("Blend sharpness", "블렌드 선명도"), ("Blending", "블렌딩"), ("Blending mode of the displayed channel", "표시된 채널의 블렌딩 모드"), ("Blur", "블러"), @@ -805,6 +804,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "텍스처 포함 USDZ"), ("UV checker", "UV 체커"), ("UV island fill", "UV 아일랜드 채우기"), + ("UV transformations", "UV 변환"), ("UV projection", "UV 투영"), ("UV tiles", "UV 타일"), ("UV tiles (UDIM)", "UV 타일 (UDIM)"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 880b62ff..7bd3d231 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -108,7 +108,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Normais curvadas"), ("Bevel", "Chanfro"), ("Black", "Preto"), - ("Blend sharpness", "Nitidez da mistura"), ("Blending", "Mesclagem"), ("Blending mode of the displayed channel", "Modo de mesclagem do canal exibido"), ("Blur", "Desfoque"), @@ -820,6 +819,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ com texturas"), ("UV checker", "Xadrez UV"), ("UV island fill", "Preenchimento de ilhas UV"), + ("UV transformations", "Transformações UV"), ("UV projection", "Projeção UV"), ("UV tiles", "Tiles UV"), ("UV tiles (UDIM)", "Tiles UV (UDIM)"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index f894f1ad..7d393f75 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -96,7 +96,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "弯曲法线"), ("Bevel", "斜角"), ("Black", "黑色"), - ("Blend sharpness", "混合锐度"), ("Blending", "混合"), ("Blending mode of the displayed channel", "所显示通道的混合模式"), ("Blur", "模糊"), @@ -766,6 +765,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "带纹理的 USDZ"), ("UV checker", "UV 棋盘格"), ("UV island fill", "UV 岛填充"), + ("UV transformations", "UV 变换"), ("UV projection", "UV 投影"), ("UV tiles", "UV 图块"), ("UV tiles (UDIM)", "UV 图块(UDIM)"), diff --git a/crates/ui-egui/tests/fill_projection_section.rs b/crates/ui-egui/tests/fill_projection_section.rs new file mode 100644 index 00000000..c46b4c7e --- /dev/null +++ b/crates/ui-egui/tests/fill_projection_section.rs @@ -0,0 +1,68 @@ +//! A fill's projection settings fold into a "UV transformations" section under the Projection combo + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_ui_egui::TextureCraftApp; + +/// The app with a new fill layer (projected as `projection`) selected in Properties, and its layer id +fn app_with_fill(projection: &str) -> (Harness<'static, TextureCraftApp>, u64) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let added = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + let layer = added["layer"].as_u64().unwrap(); + texturecraft_engine::execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": projection})).unwrap(); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + (harness, layer) +} + +fn toggle_section(harness: &mut Harness<'_, TextureCraftApp>) { + harness.get_by_label("UV transformations").click(); + harness.run_steps(3); +} + +#[test] +fn the_uv_transformations_start_open_and_fold_away() { + let (mut harness, _) = app_with_fill("uv"); + assert!(harness.query_by_label("Rotation").is_some()); + + toggle_section(&mut harness); + assert!(harness.query_by_label("Rotation").is_none()); + assert!(harness.query_by_label("Scale / tiling").is_none()); + assert!(harness.query_by_label("Projection").is_some()); + + toggle_section(&mut harness); + assert!(harness.query_by_label("Rotation").is_some()); +} + +#[test] +fn hardness_and_axis_stay_outside_the_section() { + let (mut harness, _) = app_with_fill("triplanar"); + toggle_section(&mut harness); + assert!(harness.query_by_label("Offset X").is_none()); + assert!(harness.query_by_label("Hardness").is_some()); + + let (mut harness, _) = app_with_fill("planar"); + toggle_section(&mut harness); + assert!(harness.query_by_label("Offset X").is_none()); + assert!(harness.query_by_label("Axis").is_some()); +} + +#[test] +fn each_fill_keeps_its_own_open_state() { + let (mut harness, first) = app_with_fill("uv"); + toggle_section(&mut harness); + + let added = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.fill", &json!({})).unwrap(); + let second = added["layer"].as_u64().unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": second})).unwrap(); + harness.run_steps(3); + assert!(harness.query_by_label("Rotation").is_some(), "a new fill starts open"); + + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": first})).unwrap(); + harness.run_steps(3); + assert!(harness.query_by_label("Rotation").is_none(), "the first fill stays closed"); +} From a626af86bb7f9e3009968b3c77be0444c6d883e0 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 00:10:23 +0000 Subject: [PATCH 28/73] Keep every saved state that cannot be read, and save only states that read back --- crates/ui-egui/src/ui_state_store.rs | 146 +++++++++++++++++++++------ 1 file changed, 114 insertions(+), 32 deletions(-) diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs index 467dad78..4535817d 100644 --- a/crates/ui-egui/src/ui_state_store.rs +++ b/crates/ui-egui/src/ui_state_store.rs @@ -8,16 +8,16 @@ use crate::UiState; /// eframe storage key of the UI state as JSON, where there is no file const STORAGE_KEY: &str = "ui.json"; +/// Name of the UI state in eframe's storage, before the extension, for the copies of unreadable states kept there +const STORAGE_STEM: &str = "ui"; + /// eframe storage key under which earlier builds kept the UI state, as RON const RON_STORAGE_KEY: &str = "ui"; -/// eframe storage key of a saved state this build could not fully read, where there is no file -const UNREADABLE_STORAGE_KEY: &str = "ui.unreadable.json"; - /// Largest UI state file read; a saved state is a few kilobytes const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; -/// Copies of unreadable saved states kept beside the file before saving stops +/// Copies of unreadable saved states kept before saving stops const MAX_UNREADABLE_COPIES: u32 = 10; /// The desktop's `ui.json`, set by the app before its window opens; unset, the state stays in eframe's storage @@ -27,8 +27,9 @@ pub static FILE: OnceLock = OnceLock::new(); #[derive(Default)] pub struct UiStateStore { file: Option, - unreadable: Option>, - /// The unreadable state could not be kept, so the saved one is left as it is + /// A saved state this build could not fully read and its file extension, kept by the next save + unreadable: Option<(Vec, &'static str)>, + /// A saved state could not be read or kept, so it is left as it is frozen: bool, } @@ -45,30 +46,51 @@ impl UiStateStore { self.frozen = true; return None; } - Some(file) => std::fs::read(file).ok(), + Some(file) => match std::fs::read(file) { + Ok(bytes) => Some(bytes), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(_) => { + self.frozen = true; + return None; + } + }, None => storage.and_then(|storage| storage.get_string(STORAGE_KEY)).map(String::into_bytes), }; - let Some(bytes) = saved else { - return storage.and_then(|storage| eframe::get_value::(storage, RON_STORAGE_KEY)); - }; + let Some(bytes) = saved else { return self.load_ron(storage?) }; let ui = serde_json::from_slice::(&bytes).ok(); if !ui.as_ref().is_some_and(fully_read) { - self.unreadable = Some(bytes); + self.unreadable = Some((bytes, "json")); + } + ui + } + + /// The RON state an earlier build saved; its docks never read back, so only text that does not parse is kept + fn load_ron(&mut self, storage: &dyn eframe::Storage) -> Option { + let text = storage.get_string(RON_STORAGE_KEY)?; + let ui = eframe::get_value::(storage, RON_STORAGE_KEY); + if ui.is_none() { + self.unreadable = Some((text.into_bytes(), "ron")); } ui } /// Save `ui` as JSON once an unreadable saved state is kept, and drop the RON copy of earlier builds pub fn save(&mut self, ui: &UiState, storage: &mut dyn eframe::Storage) { - if let Some(bytes) = self.unreadable.take() { - self.frozen = !self.keep_unreadable(&bytes, storage); + if let Some((bytes, extension)) = self.unreadable.take() { + self.frozen = !self.keep_unreadable(&bytes, extension, storage); } if self.frozen { return; } let Ok(json) = serde_json::to_string_pretty(ui) else { return }; + // JSON writes a non-finite number as null, which would not read back + if serde_json::from_str::(&json).is_err() { + log::warn!("the UI state was not saved: it would not read back"); + return; + } + let saved = match &self.file { Some(file) => write_file(file, json.as_bytes()), None => { @@ -81,12 +103,15 @@ impl UiStateStore { } } - /// Keep a saved state this build could not fully read, beside the file or under its own storage key - fn keep_unreadable(&self, bytes: &[u8], storage: &mut dyn eframe::Storage) -> bool { + /// Keep a saved state this build could not fully read under the first free copy name, beside the file or in storage + fn keep_unreadable(&self, bytes: &[u8], extension: &str, storage: &mut dyn eframe::Storage) -> bool { match &self.file { - Some(file) => keep_file_copy(file, bytes), + Some(file) => keep_file_copy(file, bytes, extension), None => { - storage.set_string(UNREADABLE_STORAGE_KEY, String::from_utf8_lossy(bytes).into_owned()); + let free = (1..=MAX_UNREADABLE_COPIES).map(|n| unreadable_name(STORAGE_STEM, n, extension)).find(|key| storage.get_string(key).is_none()); + let Some(key) = free else { return false }; + + storage.set_string(&key, String::from_utf8_lossy(bytes).into_owned()); true } } @@ -112,6 +137,11 @@ fn too_large(file: &Path) -> bool { std::fs::metadata(file).is_ok_and(|metadata| metadata.len() > MAX_FILE_BYTES) } +/// The `n`th copy name of an unreadable state: `.unreadable.`, then `.unreadable-N.` +fn unreadable_name(stem: &str, n: u32, extension: &str) -> String { + if n == 1 { format!("{stem}.unreadable.{extension}") } else { format!("{stem}.unreadable-{n}.{extension}") } +} + #[cfg(not(target_arch = "wasm32"))] fn write_file(file: &Path, bytes: &[u8]) -> bool { if let Some(folder) = file.parent() { @@ -126,14 +156,14 @@ fn write_file(_file: &Path, _bytes: &[u8]) -> bool { false } -/// Copy `bytes` beside `file` as the first free `.unreadable.json` or `.unreadable-N.json` -fn keep_file_copy(file: &Path, bytes: &[u8]) -> bool { +/// Copy `bytes` beside `file` under the first free copy name +fn keep_file_copy(file: &Path, bytes: &[u8], extension: &str) -> bool { use std::io::Write as _; let stem = file.file_stem().map(|stem| stem.to_string_lossy().into_owned()).unwrap_or_default(); for n in 1..=MAX_UNREADABLE_COPIES { - let name = if n == 1 { format!("{stem}.unreadable.json") } else { format!("{stem}.unreadable-{n}.json") }; - match std::fs::OpenOptions::new().write(true).create_new(true).open(file.with_file_name(name)) { + let copy_file = file.with_file_name(unreadable_name(&stem, n, extension)); + match std::fs::OpenOptions::new().write(true).create_new(true).open(copy_file) { Ok(mut copy) => return copy.write_all(bytes).is_ok(), Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} Err(_) => return false, @@ -257,7 +287,7 @@ pub(crate) mod tests { } store.save(&loaded.unwrap_or_default(), &mut storage); - let copy = if n == 0 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{}.json", n + 1) }; + let copy = unreadable_name("ui", n as u32 + 1, "json"); assert_eq!(std::fs::read_to_string(folder.join(copy)).unwrap(), *text); assert_ne!(std::fs::read_to_string(&file).unwrap(), *text, "the next save replaces it once kept"); } @@ -269,8 +299,7 @@ pub(crate) mod tests { let folder = test_folder("frozen"); let file = folder.join("ui.json"); for n in 1..=MAX_UNREADABLE_COPIES { - let name = if n == 1 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{n}.json") }; - std::fs::write(folder.join(name), "").unwrap(); + std::fs::write(folder.join(unreadable_name("ui", n, "json")), "").unwrap(); } std::fs::write(&file, "not json").unwrap(); @@ -298,17 +327,70 @@ pub(crate) mod tests { } #[test] - fn an_unreadable_layout_in_storage_is_kept_under_its_own_key() { + fn unreadable_layouts_in_storage_are_each_kept_under_a_key_of_their_own() { let mut storage = MemoryStorage::default(); UiStateStore::default().save(&UiState { dock: moved_panels(), ..UiState::default() }, &mut storage); - let bogus = storage.0[STORAGE_KEY].replacen("\"Assets\"", "\"Bogus\"", 1); - storage.0.insert(STORAGE_KEY.to_owned(), bogus.clone()); + let saved = storage.0[STORAGE_KEY].clone(); + for (n, panel) in [(1, "\"Bogus\""), (2, "\"Other\"")] { + let unreadable = saved.replacen("\"Assets\"", panel, 1); + storage.0.insert(STORAGE_KEY.to_owned(), unreadable.clone()); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).unwrap(); + assert_eq!(loaded.dock, Dock::default()); + store.save(&loaded, &mut storage); + assert_eq!(storage.0[&unreadable_name(STORAGE_STEM, n, "json")], unreadable); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } + assert_eq!(storage.0[&unreadable_name(STORAGE_STEM, 1, "json")], saved.replacen("\"Assets\"", "\"Bogus\"", 1), "the first copy stays"); + } + + #[test] + fn an_earlier_state_that_does_not_parse_is_kept_before_its_entry_goes() { + let folder = test_folder("ron"); + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + storage.0.insert(RON_STORAGE_KEY.to_owned(), "(not ron".to_owned()); + + let mut store = UiStateStore::new(file.clone()); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + let copy = match &file { + Some(_) => std::fs::read_to_string(folder.join(unreadable_name("ui", 1, "ron"))).unwrap(), + None => storage.0[&unreadable_name(STORAGE_STEM, 1, "ron")].clone(), + }; + assert_eq!(copy, "(not ron", "{file:?}"); + assert!(!storage.0.contains_key(RON_STORAGE_KEY), "{file:?}"); + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_file_that_exists_but_cannot_be_read_is_not_saved_over() { + let folder = test_folder("read-error"); + let file = folder.join("ui.json"); + // A folder in the file's place fails to read with an error other than not found + std::fs::create_dir_all(&file).unwrap(); + let mut storage = MemoryStorage::default(); + eframe::set_value(&mut storage, RON_STORAGE_KEY, &UiState::default()); + + let mut store = UiStateStore::new(Some(file.clone())); + assert!(store.load(Some(&storage)).is_none(), "the earlier state is not loaded in its place"); + store.save(&UiState::default(), &mut storage); + assert!(file.is_dir()); + assert!(storage.0.contains_key(RON_STORAGE_KEY)); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_state_that_would_not_read_back_is_not_saved() { + let mut storage = MemoryStorage::default(); let mut store = UiStateStore::default(); - let loaded = store.load(Some(&storage)).unwrap(); - assert_eq!(loaded.dock, Dock::default()); - store.save(&loaded, &mut storage); - assert_eq!(storage.0[UNREADABLE_STORAGE_KEY], bogus); - assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + store.save(&UiState { split_ratio: 0.3, ..UiState::default() }, &mut storage); + let saved = storage.0[STORAGE_KEY].clone(); + + store.save(&UiState { uv_pan: [f32::NAN, 0.0], ..UiState::default() }, &mut storage); + assert_eq!(storage.0[STORAGE_KEY], saved); } } From 56bbf26acf681d1be4d900a8c757f85c0dbb3b40 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 03:15:50 +0000 Subject: [PATCH 29/73] Bake: curvature from the normal map follows the surface, one band per edge Curvature from the normal map took a 4-texel (at 2K) difference of the tangent-space normal. The wide difference split each sharp normal change into two thin peaks with rings around small details, and the tangent map bends against a smooth-shaded low poly's own shading, so flat faces baked as concave. It now measures how fast the baked world normal turns along the surface direction of each texel step (from each low-poly triangle's UV mapping), with differences that never read uncovered texels or cross a UV tile, a 1-2-1 average across each derivative so lines are equally wide in every direction, and a soft roll-off instead of clipping. Details keeps its meaning; the default response is about 25% softer. Fixes #316 --- crates/bake/src/lib.rs | 16 ++- crates/bake/src/map.rs | 2 + crates/bake/src/map/normal_curvature.rs | 142 ++++++++++++++----- crates/bake/src/map/texel_grid.rs | 32 +++++ crates/bake/src/test/normal_map_curvature.rs | 84 +++++++++++ crates/bake/src/tests.rs | 18 +-- 6 files changed, 241 insertions(+), 53 deletions(-) create mode 100644 crates/bake/src/map/texel_grid.rs create mode 100644 crates/bake/src/test/normal_map_curvature.rs diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 67c349a4..a8b087bc 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -189,12 +189,13 @@ fn bake_in_strips( let mut scene = tracer.scene(&meshes)?; progress.done.store(0, Relaxed); - // Normal-map curvature needs a normal bake even when normal output is disabled + // Normal-map curvature needs a world normal bake even when that output is disabled let from_normal = settings.maps.curvature.parameters.method == CurvatureMethod::NormalMap && settings.maps.is_enabled(BakedMap::Curvature); let mut maps: Vec = settings.maps.enabled().collect(); - if from_normal && !maps.contains(&BakedMap::Normal) { - maps.push(BakedMap::Normal); + if from_normal && !maps.contains(&BakedMap::WorldNormal) { + maps.push(BakedMap::WorldNormal); } + let mut buffers = maps.iter().map(|map| alloc(width * height * map.components(), 0.0f32)).collect::, _>>()?; let mut covered = alloc(width * height, false)?; let mut padding_map = None; @@ -281,15 +282,18 @@ fn bake_in_strips( let mut output: BTreeMap> = maps.into_iter().zip(buffers).collect(); if from_normal { - let normal = if settings.maps.is_enabled(BakedMap::Normal) { output.get(&BakedMap::Normal).cloned() } else { output.remove(&BakedMap::Normal) }; - if let (Some(normal), Some(curvature_pixels)) = (normal, output.get_mut(&BakedMap::Curvature)) { + let world_normal = + if settings.maps.is_enabled(BakedMap::WorldNormal) { output.get(&BakedMap::WorldNormal).cloned() } else { output.remove(&BakedMap::WorldNormal) }; + if let (Some(world_normal), Some(curvature_pixels)) = (world_normal, output.get_mut(&BakedMap::Curvature)) { let parameters = settings.maps.curvature.parameters.normal_map; - map::curvature_from_normal(&normal, &covered, width, tile_size, parameters, curvature_pixels); + let grid = map::TexelGrid { covered: &covered, size: (width, height), tile_size }; + map::curvature_from_normal(&world_normal, request.mesh, request.material, &grid, parameters, curvature_pixels); if parameters.enable_seams { map::fix_seams(request.mesh, request.material, &covered, (width, height), parameters.seams_intensity, curvature_pixels); } } } + let (bounds_min, bounds_max) = request.mesh.bounds(); map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(1e-6)); if let Some(padding_map) = padding_map { diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs index 9638a140..384d9d02 100644 --- a/crates/bake/src/map.rs +++ b/crates/bake/src/map.rs @@ -12,11 +12,13 @@ pub(crate) use seam::fix_seams; mod position_projection; mod sampling; mod source; +mod texel_grid; mod traced; mod transfer; pub(crate) use bake_context::BakeContext; pub(crate) use normal_curvature::curvature_from_normal; pub(crate) use sample::Sample; +pub(crate) use texel_grid::TexelGrid; pub(crate) use traced::Traced; pub(crate) use transfer::Transfer; diff --git a/crates/bake/src/map/normal_curvature.rs b/crates/bake/src/map/normal_curvature.rs index 2cc6bfc5..c96163c7 100644 --- a/crates/bake/src/map/normal_curvature.rs +++ b/crates/bake/src/map/normal_curvature.rs @@ -1,42 +1,120 @@ -/// Divergence of the tangent-space normal map; positive curvature is convex +use rayon::prelude::*; +use texturecraft_core::NormalMapCurvatureSettings; +use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; + +use super::TexelGrid; + +/// Output slope per unit of normal turn per texel at a 2048-texel tile and Details 0.5, set by eye on a hard-surface bake +const SLOPE_AT_2K: f32 = 3.0; + +/// How fast the baked world normal turns along the low poly's surface; positive curvature is convex pub(crate) fn curvature_from_normal( - normal: &[f32], - covered: &[bool], - width: usize, - tile_size: (usize, usize), - settings: texturecraft_core::NormalMapCurvatureSettings, + world_normal: &[f32], + mesh: &Mesh, + material: usize, + grid: &TexelGrid, + settings: NormalMapCurvatureSettings, output: &mut [f32], ) { - use rayon::prelude::*; - let radius_texels = (tile_size.0.min(tile_size.1) / 512).max(1); - let strength = 2.0f32.powf((settings.details - 0.5) * 4.0); - let normal_component = |x: usize, y: usize, component: usize, fallback: f32| match covered.get(y * width + x) { - Some(true) => normal.get((y * width + x) * 3 + component).copied().unwrap_or(fallback), - _ => fallback, + let TexelGrid { covered, size, tile_size } = *grid; + let triangle_of_texel = triangle_of_each_texel(mesh, material, grid); + let surface_directions = surface_direction_of_each_triangle(mesh, size); + let normal_at = |index: usize| { + let encoded = world_normal.get(index * 3..index * 3 + 3).and_then(|components| <[f32; 3]>::try_from(components).ok()).unwrap_or([0.5, 0.5, 1.0]); + Vec3::from_array(encoded) * 2.0 - 1.0 }; - output.par_chunks_mut(width).enumerate().for_each(|(y, row)| { + + // Turn of the normal per texel, measured along the surface direction each texel axis points to + let turn_along = |axis: usize| -> Vec { + (0..covered.len()) + .into_par_iter() + .map(|index| { + let Some(direction) = + triangle_of_texel.get(index).and_then(|triangle| surface_directions.get(*triangle as usize)).and_then(|pair| pair.get(axis).copied()) + else { + return 0.0; + }; + + let step = if axis == 0 { (1, 0) } else { (0, 1) }; + let forward = grid.neighbour(index, step.0, step.1); + let backward = grid.neighbour(index, -step.0, -step.1); + let change = match (forward, backward) { + (Some(ahead), Some(behind)) => (normal_at(ahead) - normal_at(behind)) * 0.5, + (Some(ahead), None) => normal_at(ahead) - normal_at(index), + (None, Some(behind)) => normal_at(index) - normal_at(behind), + (None, None) => Vec3::ZERO, + }; + change.dot(direction) + }) + .collect() + }; + let (turn_along_x, turn_along_y) = (turn_along(0), turn_along(1)); + + let slope = SLOPE_AT_2K * tile_size.0.min(tile_size.1) as f32 / 2048.0 * 2.0f32.powf((settings.details - 0.5) * 4.0); + output.par_chunks_mut(size.0).enumerate().for_each(|(y, row)| { for (x, value) in row.iter_mut().enumerate() { - if covered.get(y * width + x) != Some(&true) { + let index = y * size.0 + x; + if covered.get(index) != Some(&true) { continue; } - let (center_x, center_y) = (normal_component(x, y, 0, 0.5), normal_component(x, y, 1, 0.5)); - let (left, right) = ( - if x % tile_size.0 >= radius_texels { normal_component(x - radius_texels, y, 0, center_x) } else { center_x }, - if x % tile_size.0 + radius_texels < tile_size.0 && x + radius_texels < width { - normal_component(x + radius_texels, y, 0, center_x) - } else { - center_x - }, - ); - let (up, down) = ( - if y % tile_size.1 >= radius_texels { normal_component(x, y - radius_texels, 1, center_y) } else { center_y }, - if y % tile_size.1 + radius_texels < tile_size.1 && y + radius_texels < covered.len() / width.max(1) { - normal_component(x, y + radius_texels, 1, center_y) - } else { - center_y - }, - ); - *value = (0.5 + ((right - left) + (up - down)) * strength).clamp(0.0, 1.0); + + // A 1-2-1 average across each derivative keeps lines equally wide in every direction + let curvature = grid.average_along(&turn_along_x, index, (0, 1)) + grid.average_along(&turn_along_y, index, (1, 0)); + + // Rises at `slope` near flat and rolls off softly, so strong edges never clip into flat white + *value = 0.5 + 0.5 * (2.0 * slope * curvature).tanh(); } }); } + +/// Unit surface directions of a texel step in x and in y on each triangle of the low poly +fn surface_direction_of_each_triangle(mesh: &Mesh, size: (usize, usize)) -> Vec<[Vec3; 2]> { + let texel_scale = Vec2::new(size.0 as f32, size.1 as f32); + (0..mesh.indices.len() / 3) + .map(|triangle| { + let corner = |slot: usize| -> Option<(Vec3, Vec2)> { + let vertex = *mesh.tri(triangle)?.get(slot)?; + Some((*mesh.positions.get(vertex)?, *mesh.uvs.get(vertex)? * texel_scale)) + }; + let (Some((first_position, first_texel)), Some((second_position, second_texel)), Some((third_position, third_texel))) = + (corner(0), corner(1), corner(2)) + else { + return [Vec3::ZERO; 2]; + }; + + let (position_edge_1, position_edge_2) = (second_position - first_position, third_position - first_position); + let (texel_edge_1, texel_edge_2) = (second_texel - first_texel, third_texel - first_texel); + let determinant = texel_edge_1.perp_dot(texel_edge_2); + // A triangle with no UV area has no texel directions + if determinant.abs() < 1e-12 { + return [Vec3::ZERO; 2]; + } + + let along_x = (position_edge_1 * texel_edge_2.y - position_edge_2 * texel_edge_1.y) / determinant; + let along_y = (position_edge_2 * texel_edge_1.x - position_edge_1 * texel_edge_2.x) / determinant; + [along_x.normalize_or_zero(), along_y.normalize_or_zero()] + }) + .collect() +} + +/// Low-poly triangle under each covered texel; edge texels covered only by antialiasing borrow a neighbour's +fn triangle_of_each_texel(mesh: &Mesh, material: usize, grid: &TexelGrid) -> Vec { + let centres = UvGBuffer::new(mesh, material, grid.size.0 as u32, grid.size.1 as u32).tri; + (0..centres.len()) + .into_par_iter() + .map(|index| { + let own = centres.get(index).copied().unwrap_or(NO_TRI); + if own != NO_TRI || grid.covered.get(index) != Some(&true) { + return own; + } + + [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)] + .into_iter() + .filter_map(|(step_x, step_y)| grid.neighbour(index, step_x, step_y)) + .map(|neighbour| centres.get(neighbour).copied().unwrap_or(NO_TRI)) + .find(|triangle| *triangle != NO_TRI) + .unwrap_or(NO_TRI) + }) + .collect() +} diff --git a/crates/bake/src/map/texel_grid.rs b/crates/bake/src/map/texel_grid.rs new file mode 100644 index 00000000..49e2b588 --- /dev/null +++ b/crates/bake/src/map/texel_grid.rs @@ -0,0 +1,32 @@ +/// Covered texels of a baked map, with UV tiles that neighbours never cross +#[derive(Clone, Copy)] +pub(crate) struct TexelGrid<'a> { + pub covered: &'a [bool], + pub size: (usize, usize), + pub tile_size: (usize, usize), +} + +impl TexelGrid<'_> { + /// The covered texel one step away in the same tile, if any + pub fn neighbour(&self, index: usize, step_x: isize, step_y: isize) -> Option { + let (width, height) = self.size; + let (x, y) = (index % width.max(1), index / width.max(1)); + let (next_x, next_y) = (x.checked_add_signed(step_x)?, y.checked_add_signed(step_y)?); + if next_x >= width || next_y >= height { + return None; + } + + let same_tile = next_x / self.tile_size.0.max(1) == x / self.tile_size.0.max(1) && next_y / self.tile_size.1.max(1) == y / self.tile_size.1.max(1); + let next = next_y * width + next_x; + (same_tile && self.covered.get(next) == Some(&true)).then_some(next) + } + + /// A 1-2-1 weighted average of `values` along `step`, over covered texels only + pub fn average_along(&self, values: &[f32], index: usize, step: (isize, isize)) -> f32 { + let centre = values.get(index).copied().unwrap_or(0.0); + let sides = [self.neighbour(index, step.0, step.1), self.neighbour(index, -step.0, -step.1)]; + let (sum, weight) = + sides.into_iter().flatten().fold((2.0 * centre, 2.0), |(sum, weight), side| (sum + values.get(side).copied().unwrap_or(0.0), weight + 1.0)); + sum / weight + } +} diff --git a/crates/bake/src/test/normal_map_curvature.rs b/crates/bake/src/test/normal_map_curvature.rs new file mode 100644 index 00000000..99ea078e --- /dev/null +++ b/crates/bake/src/test/normal_map_curvature.rs @@ -0,0 +1,84 @@ +use super::{bumped, covered_values, quad, quad_texel, settings, smooth_shaded_box, transfer}; +use texturecraft_core::{BakeSettings, BakedMap, CageSettings, CommonBakeSettings, CurvatureMethod, CurvatureSettings}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::primitives; + +fn normal_map_settings(resolution: u32) -> BakeSettings { + let mut base = settings(resolution, &[BakedMap::Curvature]); + base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; + base.common = CommonBakeSettings { dilation: 4, ..base.common }; + base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::NormalMap, ..base.maps.curvature.parameters }; + base.maps.curvature.parameters.normal_map.enable_seams = false; + base +} + +fn coordinates_beyond(position: Vec3, threshold: f32) -> usize { + position.abs().to_array().iter().filter(|coordinate| **coordinate > threshold).count() +} + +fn lowest_and_highest(values: impl IntoIterator) -> (f32, f32) { + values.into_iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lowest, highest), value| (lowest.min(value), highest.max(value))) +} + +#[test] +fn curvature_from_the_normal_map_sees_the_bump() { + let out = transfer(&quad(), &bumped(0.1, 0.12), None, &normal_map_settings(64)).unwrap(); + assert!(!out.maps.contains_key(&BakedMap::WorldNormal), "the helper world normal map is not returned"); + + let curvature = &out.maps[&BakedMap::Curvature]; + assert!(curvature[quad_texel(64, 0.0, 0.0)] > 0.55, "convex top {}", curvature[quad_texel(64, 0.0, 0.0)]); + assert!((curvature[quad_texel(64, 0.9, 0.9)] - 0.5).abs() < 0.02, "flat corner {}", curvature[quad_texel(64, 0.9, 0.9)]); +} + +#[test] +fn flat_faces_of_a_smooth_shaded_low_poly_stay_mid_grey() { + let low = smooth_shaded_box(); + let curvature = covered_values(&low, &transfer(&low, &primitives::cube(2.0), None, &normal_map_settings(256)).unwrap(), BakedMap::Curvature); + let faces: Vec = curvature.iter().filter(|(position, _)| coordinates_beyond(*position, 0.7) == 1).map(|(_, value)| *value).collect(); + + assert!(!faces.is_empty()); + assert!(faces.iter().all(|value| (value - 0.5).abs() < 0.02), "face range {:?}", lowest_and_highest(faces.iter().copied())); +} + +#[test] +fn a_rounded_edge_is_one_convex_band() { + let bevel = 0.1; + let low = smooth_shaded_box(); + let curvature = + covered_values(&low, &transfer(&low, &primitives::rounded_box(Vec3::ONE, bevel), None, &normal_map_settings(512)).unwrap(), BakedMap::Curvature); + let across_one_edge = |from: f32, to: f32| { + curvature + .iter() + .filter(move |(position, _)| (position.x - 1.0).abs() < 1e-3 && position.z.abs() < 0.3 && (from..to).contains(&position.y)) + .map(|(_, value)| *value) + }; + + let inside_the_bevel = across_one_edge(1.0 - bevel * 0.8, 0.99).fold(1.0f32, f32::min); + let next_to_the_bevel = lowest_and_highest(across_one_edge(0.5, 1.0 - bevel * 1.5)); + assert!(inside_the_bevel > 0.55, "the band dips inside the bevel: {inside_the_bevel}"); + assert!(next_to_the_bevel.0 > 0.48 && next_to_the_bevel.1 < 0.52, "next to the bevel {next_to_the_bevel:?}"); +} + +#[test] +fn a_small_bump_has_no_ring_beyond_its_skirt() { + let (resolution, sigma) = (512, 0.08); + let out = transfer(&quad(), &bumped(0.08, sigma), None, &normal_map_settings(resolution)).unwrap(); + let curvature = &out.maps[&BakedMap::Curvature]; + let ring: Vec = (0..64) + .map(|step| step as f32 / 64.0 * std::f32::consts::TAU) + .flat_map(|angle| [3.0f32, 4.0].map(|radius| curvature[quad_texel(resolution, radius * sigma * angle.cos(), radius * sigma * angle.sin())])) + .collect(); + + assert!(curvature[quad_texel(resolution, 0.0, 0.0)] > 0.6, "convex top {}", curvature[quad_texel(resolution, 0.0, 0.0)]); + assert!(ring.iter().all(|value| (value - 0.5).abs() < 0.02), "ring {:?}", lowest_and_highest(ring.iter().copied())); +} + +#[test] +fn island_borders_of_flat_faces_do_not_streak() { + let cube = primitives::cube(2.0); + let curvature = covered_values(&cube, &transfer(&cube, &cube, None, &normal_map_settings(128)).unwrap(), BakedMap::Curvature); + let faces: Vec = curvature.iter().filter(|(position, _)| coordinates_beyond(*position, 0.97) == 1).map(|(_, value)| *value).collect(); + + assert!(!faces.is_empty()); + assert!(faces.iter().all(|value| (value - 0.5).abs() < 0.01), "face range {:?}", lowest_and_highest(faces.iter().copied())); +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index bb75353e..4cd074cc 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -17,6 +17,9 @@ use super::*; #[path = "test/setting.rs"] mod setting; +#[path = "test/normal_map_curvature.rs"] +mod normal_map_curvature; + #[path = "test/tile_selection.rs"] mod tile_selection; @@ -638,21 +641,6 @@ fn bump_tilts_the_baked_normal() { assert!(height[quad_texel(64, 0.0, 0.0)] > height[quad_texel(64, 0.6, 0.6)] + 0.2, "the bump top is higher"); } -#[test] -fn curvature_from_the_normal_map_sees_the_bump() { - let s = { - let mut base = settings(64, &[BakedMap::Curvature]); - base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; - base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::NormalMap, ..base.maps.curvature.parameters }; - base - }; - let out = transfer(&quad(), &bumped(0.1, 0.4), None, &s).unwrap(); - assert!(!out.maps.contains_key(&BakedMap::Normal), "the helper normal map is not returned"); - let c = &out.maps[&BakedMap::Curvature]; - assert!(c[quad_texel(64, 0.0, 0.0)] > 0.55, "convex top {}", c[quad_texel(64, 0.0, 0.0)]); - assert!((c[quad_texel(64, 0.9, 0.9)] - 0.5).abs() < 0.02, "flat corner {}", c[quad_texel(64, 0.9, 0.9)]); -} - #[test] fn bent_normals_point_away_from_occluders() { let mut m = quad(); From 3a6a160d335ddec437cdcdb3d395eb9e47fdc0dd Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 02:55:59 +0000 Subject: [PATCH 30/73] Right-click in a view opens the Properties panel's contents at the cursor A plain right click in the 3D or 2D view (no drag, no Ctrl/Alt/Shift) opens what the Properties panel shows in a popup at the cursor; a click outside, Escape or leaving Painting closes it, and the closing click doesn't paint. Every right-drag gesture is unchanged. Closes #149 --- crates/ui-egui/src/dock.rs | 29 +- crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/menus.rs | 13 +- crates/ui-egui/src/properties_popup.rs | 79 +++++ crates/ui-egui/src/toolbar.rs | 9 +- crates/ui-egui/src/viewport.rs | 425 +++++++++++++---------- crates/ui-egui/tests/properties_popup.rs | 167 +++++++++ 7 files changed, 531 insertions(+), 195 deletions(-) create mode 100644 crates/ui-egui/src/properties_popup.rs create mode 100644 crates/ui-egui/tests/properties_popup.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 4d5a1d06..87e9d84b 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -924,23 +924,28 @@ pub(crate) fn properties_title(app: &TextureCraftApp) -> String { } pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let sel = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); - let target = app.session.target; - egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| match (&sel, target) { - (Some(l), StackTarget::Effect(e)) => effect_properties(app, ui, l, e), - (Some(l), StackTarget::Content) if matches!(l.kind, LayerKind::Fill(_)) => fill_properties(app, ui, l), - (Some(l), StackTarget::Content) if l.is_group() => { - ui.label(RichText::new(tr("A folder blends its children (pass-through). Set per-channel opacity in the layer rows.")).color(tk.text_dim)); + egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); +} + +/// What the Properties panel edits: the selected effect, fill, folder or instance, else the tool +pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); + + match (&selected, app.session.target) { + (Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect), + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), + (Some(layer), StackTarget::Content) if layer.is_group() => { + ui.label(RichText::new(tr("A folder blends its children (pass-through). Set per-channel opacity in the layer rows.")).color(tokens.text_dim)); } - (Some(l), StackTarget::Content) if l.instance_source().is_some() => instance_properties(app, ui, l), - (Some(l), StackTarget::Mask) => { - height_mask_section(app, ui, l); + (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => instance_properties(app, ui, layer), + (Some(layer), StackTarget::Mask) => { + height_mask_section(app, ui, layer); ui.separator(); tool_properties(app, ui); } _ => tool_properties(app, ui), - }); + } } /// An instance draws its source: point there for edits. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 375ff1ba..5b5045e6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -24,6 +24,7 @@ mod preview_image; mod preview_request; mod preview_worker; pub mod profile; +pub mod properties_popup; pub mod render_mode; pub mod shelf; pub mod shelf_preview; @@ -111,6 +112,8 @@ pub struct TextureCraftApp { pub last_paint_point: Option, /// The decal layer the next click in the 3D view places. pub placing_decal: Option, + /// The Properties popup a right click in a view opens. + pub properties_popup: Option, /// The wgpu state (screenshots read the renderer's targets). pub render_state: Option, /// CJK fallback fonts for the UI language. @@ -164,6 +167,7 @@ impl TextureCraftApp { render: render_mode::RenderView::default(), last_paint_point: None, placing_decal: None, + properties_popup: None, render_state: cc.wgpu_render_state.clone(), fonts: fonts::UiFonts::default(), banner: None, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 7890d436..b74aa300 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -9,6 +9,7 @@ use crate::TextureCraftApp; use crate::i18n::tr; use crate::state::{Mode, ViewLayout}; use crate::theme::Tokens; +use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; /// One menu entry. `label == "-"` is a separator; `sub` names a submenu group. #[derive(Clone, Copy, Debug)] @@ -305,7 +306,7 @@ fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { } pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { - if crate::keymap::capturing(ctx) || (ctx.memory(|m| m.focused().is_some()) && ctx.egui_wants_keyboard_input()) { + if crate::keymap::capturing(ctx) || (ctx.memory(|memory| memory.focused().is_some()) && ctx.egui_wants_keyboard_input()) { return; } @@ -327,14 +328,18 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } } + // [ and ] shrink and grow the brush by this factor per press + const BRACKET_SIZE_STEP: f32 = 1.15; let size_down = input.consume_key(Modifiers::NONE, Key::OpenBracket); let size_up = input.consume_key(Modifiers::NONE, Key::CloseBracket); if app.ui.mode == Mode::Painting && (size_down || size_up) { - let scale = if size_up { 1.15 } else { 1.0 / 1.15 }; - app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(0.0005, 0.25); + let scale = if size_up { BRACKET_SIZE_STEP } else { 1.0 / BRACKET_SIZE_STEP }; + app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { + if app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + app.properties_popup = None; + } else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.tool.path.points.clear(); app.session.tool.path.editing = None; diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs new file mode 100644 index 00000000..5c174cdd --- /dev/null +++ b/crates/ui-egui/src/properties_popup.rs @@ -0,0 +1,79 @@ +//! The Properties panel's contents in a popup at the cursor: a right click in the 3D or 2D view opens it + +use egui::{PointerButton, Pos2, Rect, Ui}; + +use crate::TextureCraftApp; +use crate::state::Mode; +use crate::theme::Tokens; + +/// The popup's width, about the docked Properties panel's +const PROPERTIES_POPUP_WIDTH: f32 = 300.0; + +/// Share of the view's height the popup fills before its contents scroll +const PROPERTIES_POPUP_MAX_HEIGHT_SHARE: f32 = 0.7; + +/// Gap the popup keeps from the view's edges, so its border stays visible beside a split line +const PROPERTIES_POPUP_VIEW_MARGIN: f32 = 4.0; + +/// The Properties popup over a view +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum PropertiesPopup { + /// Shown with its top-left corner at `at`, kept inside the view `bounds` + Open { at: Pos2, bounds: Rect }, + /// Closed by a press outside it: until every button is up, that press neither paints nor reopens it + Closing, +} + +/// The popup's area, whose rect egui remembers between frames +pub fn area_id() -> egui::Id { + egui::Id::unique("properties_popup") +} + +/// Opens the popup on a plain right click in a view; right drags and modified clicks keep their gestures +pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, view: Rect, gesture_key_held: bool) { + let free = app.ui.mode == Mode::Painting + && app.properties_popup.is_none() + && !app.session.stroke_active() + && app.placing_decal.is_none() + && !gesture_key_held + && !crate::viewport::focus_picking(ui.ctx()) + && ui.input(|input| input.modifiers.is_none()); + if !free || !response.clicked_by(PointerButton::Secondary) { + return; + } + + if let Some(at) = response.interact_pointer_pos() { + app.properties_popup = Some(PropertiesPopup::Open { at, bounds: view }); + } +} + +/// Draws the open popup and closes it on a press outside it or when the app leaves Painting +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let (any_down, pressed_at) = ctx.input(|input| (input.pointer.any_down(), input.pointer.press_origin().filter(|_| input.pointer.any_pressed()))); + match app.properties_popup { + _ if app.ui.mode != Mode::Painting => app.properties_popup = None, + Some(PropertiesPopup::Closing) if !any_down => app.properties_popup = None, + Some(PropertiesPopup::Open { .. }) => { + let shown = ctx.memory(|memory| memory.area_rect(area_id())); + let outside = pressed_at.is_some_and(|at| shown.is_some_and(|rect| !rect.contains(at))); + // A press in one of the popup's own dropdowns lands outside its area + if outside && !egui::Popup::is_any_open(ctx) { + app.properties_popup = Some(PropertiesPopup::Closing); + } + } + _ => {} + } + + let Some(PropertiesPopup::Open { at, bounds }) = app.properties_popup else { return }; + let tokens = Tokens::get(ctx); + egui::Area::new(area_id()).order(egui::Order::Foreground).fixed_pos(at).constrain_to(bounds.shrink(PROPERTIES_POPUP_VIEW_MARGIN)).show(ctx, |ui| { + egui::Frame::popup(ui.style()).fill(tokens.panel).show(ui, |ui| { + ui.set_width(PROPERTIES_POPUP_WIDTH); + // The area's remembered size would otherwise cap the scroll height + ui.set_max_height(bounds.height() * PROPERTIES_POPUP_MAX_HEIGHT_SHARE); + // A floating bar would cover the sliders' right-aligned values + ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); + egui::ScrollArea::vertical().id_salt("properties_popup_scroll").show(ui, |ui| crate::dock::properties_contents(app, ui)); + }); + }); +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 897d305f..eee357f7 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -202,11 +202,14 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: }); } +/// Largest brush radius as a fraction of the mesh diagonal; size sliders show it as 100 +pub(crate) const MAX_BRUSH_SIZE: f32 = 0.25; + +/// Smallest brush radius as a fraction of the mesh diagonal +pub(crate) const MIN_BRUSH_SIZE: f32 = 0.0005; + /// The selected tool's icon and its settings fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) { - // Brush radius limits as a fraction of the mesh diagonal; the slider shows the maximum as 100 - const MAX_BRUSH_SIZE: f32 = 0.25; - const MIN_BRUSH_SIZE: f32 = 0.0005; const DEFAULT_LAZY_DISTANCE_PX: f32 = 20.0; const TOOL_ICON_SIZE: f32 = 15.0; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4ebe79b3..f20210d4 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -4,10 +4,10 @@ use std::sync::Mutex; use egui::emath::GuiRounding as _; -use egui::{Color32, PointerButton, Pos2, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; +use egui::{Color32, PointerButton, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; use serde_json::json; use texturecraft_engine::camera_cmds::DEFAULT_CAMERA; -use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::glam::{Vec2, Vec3}; use texturecraft_engine::{Tool, ViewMode}; use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind}; @@ -17,6 +17,7 @@ use crate::gpu::ViewCallback; use crate::i18n::{tr, trf}; use crate::state::ViewLayout; use crate::theme::Tokens; +use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; pub const VIEW_3D: u64 = 1; pub const VIEW_2D: u64 = 2; @@ -51,13 +52,13 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { } let tokens = Tokens::get(ui.ctx()); - let aux = match app.session.view { + let aux_view = match app.session.view { _ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing => Some(crate::gpu::AuxView::QuickMask), ViewMode::MeshMap(map) => Some(crate::gpu::AuxView::MeshMap(map)), ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)), _ => None, }; - let mut sync = PendingSync(Some(aux)); + let mut sync = PendingSync(Some(aux_view)); let full = ui.available_rect_before_wrap(); path_keys(app, ui); @@ -86,6 +87,8 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { } } + crate::properties_popup::show(app, ui.ctx()); + if mode == crate::state::Mode::Rendering { crate::render_mode::show(app, ui, full); } else if app.render.is_active() { @@ -159,6 +162,9 @@ const UV_VIEW_MIN_ZOOM: f32 = 0.1; /// Highest 2D zoom, for the wheel and the divider (inside the renderer's own limit of 64) const UV_VIEW_MAX_ZOOM: f32 = 40.0; +/// UV zoom change per point of mouse wheel, as a fraction of the zoom +const UV_WHEEL_ZOOM_PER_POINT: f32 = 0.002; + /// The 2D view's width when the split divider is at `divider_x` fn uv_view_width(full: Rect, divider_x: f32) -> f32 { (full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0) @@ -407,119 +413,157 @@ fn axis_gizmo(ui: &Ui, rect: Rect, app: &TextureCraftApp, uv: bool) { } } +/// Camera turn per point of a drag (radians) +const ORBIT_RADIANS_PER_POINT: f32 = 0.008; + +/// Camera zoom per point of an Alt+right drag +const DRAG_ZOOM_PER_POINT: f32 = 0.01; + +/// Camera zoom per point of mouse wheel +const WHEEL_ZOOM_PER_POINT: f32 = 0.0025; + +/// Environment light turn per point of a Shift+right drag (degrees) +const LIGHT_DEGREES_PER_POINT: f32 = 0.5; + +/// Brush size change per point of Shift+wheel, as a fraction of the size +const WHEEL_BRUSH_SIZE_PER_POINT: f32 = 0.002; + +/// Stencil turn per point of an S+left drag (degrees) +const STENCIL_DEGREES_PER_POINT: f32 = 0.4; + +/// Stencil scale change per point of an S+right drag, as a fraction of the scale +const STENCIL_SCALE_PER_POINT: f32 = 0.005; + +/// Smallest stencil scale an S+right drag reaches +const MIN_STENCIL_SCALE: f32 = 0.05; + +/// Largest stencil scale an S+right drag reaches +const MAX_STENCIL_SCALE: f32 = 10.0; + +/// Smallest viewport the camera projects into, so a collapsed view keeps a usable aspect (points) +const MIN_CAMERA_VIEWPORT: f32 = 16.0; + fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { - let resp = ui.interact(rect, ui.scope_id().with("view3d"), Sense::click_and_drag()); + let response = ui.interact(rect, ui.scope_id().with("view3d"), Sense::click_and_drag()); app.viewport_rect = rect; let size = rect.size(); - app.session.viewport = Vec2::new(size.x.max(16.0), size.y.max(16.0)); - let (alt, shift) = ui.input(|i| (i.modifiers.alt, i.modifiers.shift)); - let local = |p: egui::Pos2| Vec2::new(p.x - rect.left(), p.y - rect.top()); - let adjusting = brush_drag(app, ui, &resp); - let navigating = !adjusting && (alt || ui.input(|i| i.pointer.middle_down() || i.pointer.secondary_down())); + app.session.viewport = Vec2::new(size.x.max(MIN_CAMERA_VIEWPORT), size.y.max(MIN_CAMERA_VIEWPORT)); + let (alt, shift) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift)); + let local = |pointer: egui::Pos2| Vec2::new(pointer.x - rect.left(), pointer.y - rect.top()); + let adjusting = brush_drag(app, ui, &response); + let navigating = !adjusting && (alt || ui.input(|input| input.pointer.middle_down() || input.pointer.secondary_down())); - // Navigation (S + drag manipulates the projection stencil instead, below). - let delta = ui.input(|i| i.pointer.delta()); - let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|i| i.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); + // Navigation; S + drag moves the projection stencil instead, below + let delta = ui.input(|input| input.pointer.delta()); + let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); let stencil_drag = s_held && app.session.tool.stencil.is_some(); if stencil_drag || adjusting { - // The stencil moves, turns and scales instead of the camera (handled below), or the - // brush changes. - } else if resp.dragged_by(PointerButton::Middle) { + // The stencil or the brush changes instead of the camera + } else if response.dragged_by(PointerButton::Middle) { app.session.camera.pan(delta.x / size.y, delta.y / size.y); - } else if alt && resp.dragged_by(PointerButton::Primary) { - app.session.camera.orbit(delta.x * 0.008, delta.y * 0.008); - } else if resp.dragged_by(PointerButton::Secondary) { + } else if alt && response.dragged_by(PointerButton::Primary) { + app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT); + } else if response.dragged_by(PointerButton::Secondary) { if alt { - app.session.camera.zoom(-delta.y * 0.01); + app.session.camera.zoom(-delta.y * DRAG_ZOOM_PER_POINT); } else if shift { - // Shift + right drag turns the environment light. - let d = &mut app.session.doc.project.display; - d.env_rotation = (d.env_rotation + delta.x * 0.5).rem_euclid(360.0); + let display = &mut app.session.doc.project.display; + display.env_rotation = (display.env_rotation + delta.x * LIGHT_DEGREES_PER_POINT).rem_euclid(360.0); } else { - app.session.camera.orbit(delta.x * 0.008, delta.y * 0.008); + app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT); } } - if resp.hovered() { - let scroll = ui.input(|i| i.smooth_scroll_delta.y); + + if response.hovered() { + let scroll = ui.input(|input| input.smooth_scroll_delta.y); if scroll != 0.0 { if shift && app.ui.mode == crate::state::Mode::Painting { let brush = &mut app.session.tool.brush; - brush.size = (brush.size * (1.0 + scroll * 0.002)).clamp(0.0005, 0.25); + brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } else { - app.session.camera.zoom(scroll * 0.0025); + app.session.camera.zoom(scroll * WHEEL_ZOOM_PER_POINT); } } } - // Touch screens: two fingers orbit and pinch zooms, three fingers pan. A second finger - // cancels the stroke the first one started, so navigating leaves no paint behind. - let touch = ui.input(|i| i.multi_touch()).filter(|_| resp.contains_pointer() || resp.dragged()); - if let Some(t) = touch { + // Touch: two fingers orbit and pinch zooms, three pan; a second finger cancels the first one's stroke + let touch = ui.input(|input| input.multi_touch()).filter(|_| response.contains_pointer() || response.dragged()); + if let Some(gesture) = touch { if app.session.stroke_active() { app.session.cancel_stroke(); } - let d = t.translation_delta; - if t.num_touches >= 3 { - app.session.camera.pan(d.x / size.y, d.y / size.y); + + let moved = gesture.translation_delta; + if gesture.num_touches >= 3 { + app.session.camera.pan(moved.x / size.y, moved.y / size.y); } else { - app.session.camera.orbit(d.x * 0.008, d.y * 0.008); + app.session.camera.orbit(moved.x * ORBIT_RADIANS_PER_POINT, moved.y * ORBIT_RADIANS_PER_POINT); } - if t.zoom_delta.is_finite() && t.zoom_delta > 0.0 { - app.session.camera.zoom(t.zoom_delta.ln()); + if gesture.zoom_delta.is_finite() && gesture.zoom_delta > 0.0 { + app.session.camera.zoom(gesture.zoom_delta.ln()); } } - // Stencil: S + left drag rotates, S + right drag scales, S + middle drag moves. - if s_held && let Some(st) = app.session.tool.stencil.as_mut() { - if resp.dragged_by(PointerButton::Primary) { - st.rotation = (st.rotation + delta.x * 0.4).rem_euclid(360.0); - } else if resp.dragged_by(PointerButton::Secondary) { - st.scale = (st.scale * (1.0 + delta.x * 0.005)).clamp(0.05, 10.0); - } else if resp.dragged_by(PointerButton::Middle) { - st.center[0] += delta.x / size.x * 2.0; - st.center[1] -= delta.y / size.y * 2.0; + // Stencil: S + left drag turns it, S + right drag scales it, S + middle drag moves it + if s_held && let Some(stencil) = app.session.tool.stencil.as_mut() { + if response.dragged_by(PointerButton::Primary) { + stencil.rotation = (stencil.rotation + delta.x * STENCIL_DEGREES_PER_POINT).rem_euclid(360.0); + } else if response.dragged_by(PointerButton::Secondary) { + stencil.scale = (stencil.scale * (1.0 + delta.x * STENCIL_SCALE_PER_POINT)).clamp(MIN_STENCIL_SCALE, MAX_STENCIL_SCALE); + } else if response.dragged_by(PointerButton::Middle) { + stencil.center[0] += delta.x / size.x * 2.0; + stencil.center[1] -= delta.y / size.y * 2.0; } } - // Clone source: V + click. + + // Clone source: V + click let v_held = clone_source_key(app, ui); if v_held && !alt - && (resp.clicked_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) - && let Some(p) = resp.interact_pointer_pos() + && (response.clicked_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary)) + && let Some(pointer) = response.interact_pointer_pos() { - let (q, vp) = (local(p), app.session.viewport); - app.run("tool.cloneSource", json!({"x": q.x, "y": q.y, "viewport": [vp.x, vp.y]})); + let (at, viewport) = (local(pointer), app.session.viewport); + app.run("tool.cloneSource", json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); } - // Depth of field focus pick: a click focuses there instead of painting. + + // Depth of field focus pick: a click focuses there instead of painting let focus_pick = focus_picking(ui.ctx()); if focus_pick { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt - && resp.clicked_by(PointerButton::Primary) - && let Some(p) = resp.interact_pointer_pos() + && response.clicked_by(PointerButton::Primary) + && let Some(pointer) = response.interact_pointer_pos() { - let (q, vp) = (local(p), app.session.viewport); - app.run("viewport.focusAt", json!({"x": q.x, "y": q.y, "viewport": [vp.x, vp.y]})); + let (at, viewport) = (local(pointer), app.session.viewport); + app.run("viewport.focusAt", json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); set_focus_picking(ui.ctx(), false); } } - // Decal placement: a click moves the decal being placed there. + + // Decal placement: a click moves the decal being placed there let placing = app.placing_decal.filter(|_| app.ui.mode == crate::state::Mode::Painting); if let Some(layer) = placing { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt - && resp.clicked_by(PointerButton::Primary) - && let Some(p) = resp.interact_pointer_pos() + && response.clicked_by(PointerButton::Primary) + && let Some(pointer) = response.interact_pointer_pos() { - let (q, vp) = (local(p), app.session.viewport); - app.run("layer.decal.set", json!({"layer": layer.0, "x": q.x, "y": q.y, "viewport": [vp.x, vp.y]})); + let (at, viewport) = (local(pointer), app.session.viewport); + app.run("layer.decal.set", json!({"layer": layer.0, "x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); app.placing_decal = None; } } - // The selected decal's frame and handles: drag to move, scale or turn it. - let decal_drag = !alt && !s_held && !v_held && !focus_pick && placing.is_none() && touch.is_none() && decal_input(app, ui, &resp, rect); - // Painting. + + crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held); + let popup = app.properties_popup.is_some(); + + // The selected decal's frame and handles: drag to move, scale or turn it + let decal_drag = !alt && !s_held && !v_held && !focus_pick && !popup && placing.is_none() && touch.is_none() && decal_input(app, ui, &response, rect); + + // Painting let painting = app.ui.mode == crate::state::Mode::Painting + && !popup && !alt && !adjusting && !s_held @@ -529,42 +573,42 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && touch.is_none() && !decal_drag; let path_tool = app.session.tool.tool == Tool::Path; - let vp = app.session.viewport; - let show = |app: &TextureCraftApp, p: Vec3| project(app, rect, p); + let viewport = app.session.viewport; + let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point); if painting && path_tool { - path_input(app, ui, &resp, false, |app, p| app.session.pick(local(p), vp).map(|h| h.pos), show); + path_input(app, ui, &response, false, |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show); } else if painting { let pressure = pen_pressure(ui); - if resp.drag_started_by(PointerButton::Primary) || resp.clicked_by(PointerButton::Primary) { - // Shift+click paints a straight line from where the last stroke ended. + if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { + // Shift+click paints a straight line from where the last stroke ended let line_from = if shift { app.last_paint_point } else { None }; - if let Some(p) = resp.interact_pointer_pos() { - match app.session.begin_stroke(line_from.unwrap_or(local(p)), app.session.viewport, pressure) { + if let Some(pointer) = response.interact_pointer_pos() { + match app.session.begin_stroke(line_from.unwrap_or(local(pointer)), app.session.viewport, pressure) { Ok(_) => { if line_from.is_some() { - app.session.continue_stroke(local(p), pressure); + app.session.continue_stroke(local(pointer), pressure); } - app.last_paint_point = Some(local(p)); + app.last_paint_point = Some(local(pointer)); } - Err(e) => app.toast(e.to_string(), true), + Err(error) => app.toast(error.to_string(), true), } } - if resp.clicked_by(PointerButton::Primary) - && let Err(e) = app.session.end_stroke() + if response.clicked_by(PointerButton::Primary) + && let Err(error) = app.session.end_stroke() { - app.toast(e.to_string(), true); + app.toast(error.to_string(), true); } - } else if resp.dragged_by(PointerButton::Primary) + } else if response.dragged_by(PointerButton::Primary) && app.session.stroke_active() - && let Some(p) = resp.interact_pointer_pos() + && let Some(pointer) = response.interact_pointer_pos() { - app.session.continue_stroke(local(p), pressure); - app.last_paint_point = Some(local(p)); + app.session.continue_stroke(local(pointer), pressure); + app.last_paint_point = Some(local(pointer)); } - if resp.drag_stopped_by(PointerButton::Primary) - && let Err(e) = app.session.end_stroke() + if response.drag_stopped_by(PointerButton::Primary) + && let Err(error) = app.session.end_stroke() { - app.toast(e.to_string(), true); + app.toast(error.to_string(), true); } } @@ -573,43 +617,45 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin size: frame_size_in_pixels(ui, rect), kind: ViewKind::Scene, camera: app.session.camera, - shade: Shade { highlight: drop_highlight(app, ui, &resp), ..shade(app) }, - visible: app.session.doc.project.texture_sets.iter().map(|t| t.visible).collect(), + shade: Shade { highlight: drop_highlight(app, ui, &response), ..shade(app) }, + visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); - // Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush - crate::shelf::drop_target(app, ui, &resp, crate::shelf::DropZone::View3d); - // Brush cursor. + // Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush + crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); + + // Brush cursor; while a Ctrl+drag changes the brush it stays where the drag began if app.ui.mode == crate::state::Mode::Painting && !navigating - && resp.hovered() + && response.hovered() && brush_tool(app.session.tool.tool) - // While a Ctrl+drag changes the brush, its cursor stays where the drag began. - && let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { resp.hover_pos() } - && let Some(hit) = app.session.pick(local(hp), app.session.viewport) + && let Some(hover_pos) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos() } + && let Some(hit) = app.session.pick(local(hover_pos), app.session.viewport) { ui.ctx().set_cursor_icon(egui::CursorIcon::None); brush_cursor(app, ui, rect, hit.pos, hit.nrm); if app.session.tool.tool == Tool::Clone - && let Some(src) = app.session.clone_source_point(Some(hit.uv)) + && let Some(source) = app.session.clone_source_point(Some(hit.uv)) { - clone_marker(app, ui, rect, src); + clone_marker(app, ui, rect, source); } - // Shift: preview the straight line Shift+click paints from the last stroke. + + // Shift: preview the straight line Shift+click paints from the last stroke if shift && !path_tool && let Some(from) = app.last_paint_point { - rubber_band(ui, rect, pos2(rect.left() + from.x, rect.top() + from.y), hp); + rubber_band(ui, rect, pos2(rect.left() + from.x, rect.top() + from.y), hover_pos); } } + if app.ui.mode == crate::state::Mode::Painting && path_tool { - path_overlay(app, ui, rect, &resp, false, show); + path_overlay(app, ui, rect, &response, false, show); } stencil_overlay(app, ui, rect); decal_overlay(app, ui, rect); - brush_readout(app, ui, &resp, adjusting); + brush_readout(app, ui, &response, adjusting); if app.session.quick_mask.editing { ui.painter_at(rect).text( rect.left_top() + vec2(12.0, 40.0), @@ -1021,15 +1067,23 @@ fn brush_readout(app: &TextureCraftApp, ui: &Ui, resp: &egui::Response, adjustin p.galley(r.min + vec2(6.0, 3.0), g, tk.text_strong); } -/// Brush change for a Ctrl+drag by `d` points: `right` sets the size (x) and hardness (y), else -/// the flow (x) and angle (y); dragging up raises hardness and angle. -fn adjust_brush(b: &mut texturecraft_engine::paint::BrushSettings, right: bool, d: egui::Vec2) { +/// Size fraction, hardness and flow change per point of a Ctrl+drag +const CTRL_DRAG_RATE_PER_POINT: f32 = 0.005; + +/// Brush angle change per point of a Ctrl+left drag (degrees) +const CTRL_DRAG_DEGREES_PER_POINT: f32 = 0.5; + +/// Highest hardness a Ctrl+right drag sets +const CTRL_DRAG_MAX_HARDNESS: f32 = 0.999; + +/// Brush change for a Ctrl+drag by `drag` points: a right drag sets the size (x) and hardness (y), a left drag the flow (x) and angle (y); up raises hardness and angle +fn adjust_brush(brush: &mut texturecraft_engine::paint::BrushSettings, right: bool, drag: egui::Vec2) { if right { - b.size = (b.size * (1.0 + d.x * 0.005)).clamp(0.0005, 0.25); - b.hardness = (b.hardness - d.y * 0.005).clamp(0.0, 0.999); + brush.size = (brush.size * (1.0 + drag.x * CTRL_DRAG_RATE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + brush.hardness = (brush.hardness - drag.y * CTRL_DRAG_RATE_PER_POINT).clamp(0.0, CTRL_DRAG_MAX_HARDNESS); } else { - b.flow = (b.flow + d.x * 0.005).clamp(0.0, 1.0); - b.angle = (b.angle - d.y * 0.5 + 180.0).rem_euclid(360.0) - 180.0; + brush.flow = (brush.flow + drag.x * CTRL_DRAG_RATE_PER_POINT).clamp(0.0, 1.0); + brush.angle = (brush.angle - drag.y * CTRL_DRAG_DEGREES_PER_POINT + 180.0).rem_euclid(360.0) - 180.0; } } @@ -1095,136 +1149,155 @@ fn pen_pressure(ui: &Ui) -> f32 { } fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { - let tk = Tokens::get(ui.ctx()); - let resp = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); let size = rect.size(); - let alt = ui.input(|i| i.modifiers.alt); - let adjusting = brush_drag(app, ui, &resp); - let delta = ui.input(|i| i.pointer.delta()); - if resp.dragged_by(PointerButton::Middle) || (alt && resp.dragged_by(PointerButton::Primary)) { + let alt = ui.input(|input| input.modifiers.alt); + let adjusting = brush_drag(app, ui, &response); + + // Pan with a middle drag or Alt+left drag, zoom with the wheel about the cursor + let delta = ui.input(|input| input.pointer.delta()); + if response.dragged_by(PointerButton::Middle) || (alt && response.dragged_by(PointerButton::Primary)) { app.ui.uv_pan[0] += delta.x / size.x * 2.0; app.ui.uv_pan[1] -= delta.y / size.y * 2.0; } - if resp.hovered() { - let scroll = ui.input(|i| i.smooth_scroll_delta.y); + if response.hovered() { + let scroll = ui.input(|input| input.smooth_scroll_delta.y); if scroll != 0.0 { - let old = app.ui.uv_zoom; - let new = (old * (1.0 + scroll * 0.002)).clamp(UV_VIEW_MIN_ZOOM, UV_VIEW_MAX_ZOOM); - // Zoom about the cursor. - if let Some(hp) = resp.hover_pos() { - let c = [(hp.x - rect.left()) / size.x * 2.0 - 1.0, 1.0 - (hp.y - rect.top()) / size.y * 2.0]; - for k in 0..2 { - app.ui.uv_pan[k] = c[k] - (c[k] - app.ui.uv_pan[k]) * new / old; + let old_zoom = app.ui.uv_zoom; + let new_zoom = (old_zoom * (1.0 + scroll * UV_WHEEL_ZOOM_PER_POINT)).clamp(UV_VIEW_MIN_ZOOM, UV_VIEW_MAX_ZOOM); + if let Some(hover_pos) = response.hover_pos() { + let cursor = [(hover_pos.x - rect.left()) / size.x * 2.0 - 1.0, 1.0 - (hover_pos.y - rect.top()) / size.y * 2.0]; + for axis in 0..2 { + app.ui.uv_pan[axis] = cursor[axis] - (cursor[axis] - app.ui.uv_pan[axis]) * new_zoom / old_zoom; } } - app.ui.uv_zoom = new; + app.ui.uv_zoom = new_zoom; } } + + // Conversions between the view's points and the texture set's UV space let ts = app.session.ts(); let set = app.session.doc.project.texture_sets.get(ts); - let [sx, sy] = texturecraft_render::uv_view_scale(size.x / size.y.max(1.0), app.ui.uv_zoom, set.map_or((1, 1), |t| t.size())); + let [scale_x, scale_y] = texturecraft_render::uv_view_scale(size.x / size.y.max(1.0), app.ui.uv_zoom, set.map_or((1, 1), |texture_set| texture_set.size())); let pan = app.ui.uv_pan; - let to_uv = |p: egui::Pos2| { - let xc = (p.x - rect.left()) / size.x * 2.0 - 1.0; - let yc = 1.0 - (p.y - rect.top()) / size.y * 2.0; - Vec2::new(((xc - pan[0]) / sx + 1.0) * 0.5, (1.0 - (yc - pan[1]) / sy) * 0.5) + let to_uv = |pointer: egui::Pos2| { + let clip_x = (pointer.x - rect.left()) / size.x * 2.0 - 1.0; + let clip_y = 1.0 - (pointer.y - rect.top()) / size.y * 2.0; + Vec2::new(((clip_x - pan[0]) / scale_x + 1.0) * 0.5, (1.0 - (clip_y - pan[1]) / scale_y) * 0.5) }; - let to = |u: f32, v: f32| { - let x = (u * 2.0 - 1.0) * sx + pan[0]; - let y = (1.0 - v * 2.0) * sy + pan[1]; - pos2(rect.left() + (x * 0.5 + 0.5) * size.x, rect.top() + (0.5 - y * 0.5) * size.y) + let to_screen = |u: f32, v: f32| { + let clip_x = (u * 2.0 - 1.0) * scale_x + pan[0]; + let clip_y = (1.0 - v * 2.0) * scale_y + pan[1]; + pos2(rect.left() + (clip_x * 0.5 + 0.5) * size.x, rect.top() + (0.5 - clip_y * 0.5) * size.y) }; - let show = |_: &TextureCraftApp, p: Vec3| Some(to(p.x, p.y)); + let show = |_: &TextureCraftApp, point: Vec3| Some(to_screen(point.x, point.y)); let path_tool = app.session.tool.tool == Tool::Path; - // Clone source (V + click) and painting in UV space. + + // Clone source: V + click let v_held = clone_source_key(app, ui); if v_held - && (resp.clicked_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) - && let Some(p) = resp.interact_pointer_pos() + && (response.clicked_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary)) + && let Some(pointer) = response.interact_pointer_pos() { - let uv = to_uv(p); + let uv = to_uv(pointer); app.run("tool.cloneSource", json!({"uv": [uv.x, uv.y]})); } + let bake_paint_on = app.ui.mode == crate::state::Mode::Baking && app.ui.bake_paint_brush.on && !alt; if bake_paint_on { - bake_paint_input(app, ui, &resp, &to_uv); + bake_paint_input(app, ui, &response, &to_uv); } - let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !adjusting && !v_held; + + crate::properties_popup::open_on_right_click(app, ui, &response, rect, v_held); + + // Painting in UV space + let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held; if painting && path_tool { - path_input(app, ui, &resp, true, |_, p| Some(to_uv(p).extend(0.0)), show); + path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); } else if painting { let pressure = pen_pressure(ui); - if resp.drag_started_by(PointerButton::Primary) || resp.clicked_by(PointerButton::Primary) { - if let Some(p) = resp.interact_pointer_pos() - && let Err(e) = app.session.begin_stroke_uv(to_uv(p), pressure) + if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { + if let Some(pointer) = response.interact_pointer_pos() + && let Err(error) = app.session.begin_stroke_uv(to_uv(pointer), pressure) { - app.toast(e.to_string(), true); + app.toast(error.to_string(), true); } - if resp.clicked_by(PointerButton::Primary) - && let Err(e) = app.session.end_stroke() + if response.clicked_by(PointerButton::Primary) + && let Err(error) = app.session.end_stroke() { - app.toast(e.to_string(), true); + app.toast(error.to_string(), true); } - } else if resp.dragged_by(PointerButton::Primary) + } else if response.dragged_by(PointerButton::Primary) && app.session.stroke_active() - && let Some(p) = resp.interact_pointer_pos() + && let Some(pointer) = response.interact_pointer_pos() { - app.session.continue_stroke_uv(to_uv(p), pressure); + app.session.continue_stroke_uv(to_uv(pointer), pressure); } - if resp.drag_stopped_by(PointerButton::Primary) - && let Err(e) = app.session.end_stroke() + if response.drag_stopped_by(PointerButton::Primary) + && let Err(error) = app.session.end_stroke() { - app.toast(e.to_string(), true); + app.toast(error.to_string(), true); } } - if resp.double_clicked() && !(painting && path_tool) { + if response.double_clicked() && !(painting && path_tool) { app.ui.uv_zoom = 1.0; app.ui.uv_pan = [0.0, 0.0]; } + let frame = Frame { view_id: VIEW_2D, size: frame_size_in_pixels(ui, rect), kind: ViewKind::Uv { ts, zoom: app.ui.uv_zoom, pan: app.ui.uv_pan }, camera: app.session.camera, shade: shade(app), - visible: app.session.doc.project.texture_sets.iter().map(|t| t.visible).collect(), + visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); - crate::shelf::drop_target(app, ui, &resp, crate::shelf::DropZone::View2d); - // The UV tile outlines (numbered for UDIM sets) and the path being edited. + crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View2d); + + // The UV tile outlines (numbered for UDIM sets) and the path being edited let painter = ui.painter_at(rect); let set = app.session.doc.project.texture_sets.get(ts); - let outline = |r: Rect| painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::from_white_alpha(40)), egui::StrokeKind::Outside); - match set.and_then(|t| Some((t, t.tile_grid()?))) { - Some((t, g)) => { - for (udim, (bx, by)) in t.uv_tiles.iter().filter_map(|u| Some((*u, g.block(*u)?))) { - // A tile smaller than its block fills the block's top-left corner. - let (u0, v0, k) = (bx as f32 / g.cols as f32, by as f32 / g.rows as f32, t.tile_scale(udim)); - let r = Rect::from_two_pos(to(u0, v0), to(u0 + k / g.cols as f32, v0 + k / g.rows as f32)); - outline(r); - painter.text(r.left_top() + vec2(6.0, 4.0), egui::Align2::LEFT_TOP, udim.to_string(), egui::FontId::proportional(11.0), tk.viewport_text); + let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(40)), egui::StrokeKind::Outside); + match set.and_then(|texture_set| Some((texture_set, texture_set.tile_grid()?))) { + Some((texture_set, grid)) => { + for (udim, (block_x, block_y)) in texture_set.uv_tiles.iter().filter_map(|udim| Some((*udim, grid.block(*udim)?))) { + // A tile smaller than its block fills the block's top-left corner + let (u0, v0) = (block_x as f32 / grid.cols as f32, block_y as f32 / grid.rows as f32); + let tile_scale = texture_set.tile_scale(udim); + let tile = Rect::from_two_pos(to_screen(u0, v0), to_screen(u0 + tile_scale / grid.cols as f32, v0 + tile_scale / grid.rows as f32)); + outline(tile); + painter.text( + tile.left_top() + vec2(6.0, 4.0), + egui::Align2::LEFT_TOP, + udim.to_string(), + egui::FontId::proportional(11.0), + tokens.viewport_text, + ); } } None => { - outline(Rect::from_two_pos(to(0.0, 0.0), to(1.0, 1.0))); + outline(Rect::from_two_pos(to_screen(0.0, 0.0), to_screen(1.0, 1.0))); } } if app.ui.mode == crate::state::Mode::Painting && path_tool { - path_overlay(app, ui, rect, &resp, true, show); + path_overlay(app, ui, rect, &response, true, show); } + if app.ui.mode == crate::state::Mode::Baking { - bake_paint_overlay(app, ui, &painter, to(0.0, 1.0), to(1.0, 0.0)); - if bake_paint_on && let Some(hover) = resp.hover_pos() { - let r = (to(app.ui.bake_paint_brush.radius, 0.0).x - to(0.0, 0.0).x).abs().max(2.0); - painter.circle_stroke(hover, r, Stroke::new(1.0, Color32::from_white_alpha(200))); + bake_paint_overlay(app, ui, &painter, to_screen(0.0, 1.0), to_screen(1.0, 0.0)); + if bake_paint_on && let Some(hover) = response.hover_pos() { + let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(2.0); + painter.circle_stroke(hover, radius, Stroke::new(1.0, Color32::from_white_alpha(200))); } } - brush_readout(app, ui, &resp, adjusting); + + brush_readout(app, ui, &response, adjusting); view_header(app, ui, rect, "v2d"); axis_gizmo(ui, rect, app, true); - let name = app.session.doc.project.texture_sets.get(ts).map(|t| t.name.clone()).unwrap_or_default(); - ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tk.viewport_text); - let _ = (RichText::new(""), Channel::BaseColor); + let name = app.session.doc.project.texture_sets.get(ts).map(|texture_set| texture_set.name.clone()).unwrap_or_default(); + ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tokens.viewport_text); } /// Paint the skew map under the pointer in the 2D view (a click is one dab, a drag a stroke). diff --git a/crates/ui-egui/tests/properties_popup.rs b/crates/ui-egui/tests/properties_popup.rs new file mode 100644 index 00000000..8d3b413f --- /dev/null +++ b/crates/ui-egui/tests/properties_popup.rs @@ -0,0 +1,167 @@ +//! A plain right click in a view opens the Properties panel's contents at the cursor; right drags keep their gestures + +use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::LayerKind; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::properties_popup::{self, PropertiesPopup}; +use texturecraft_ui_egui::state::{Mode, ViewLayout}; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness +} + +fn view_center(harness: &Harness<'_, TextureCraftApp>) -> Pos2 { + harness.state().viewport_rect.center() +} + +fn is_open(harness: &Harness<'_, TextureCraftApp>) -> bool { + matches!(harness.state().properties_popup, Some(PropertiesPopup::Open { .. })) +} + +/// Press and release `button` at `at` without moving +fn click(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, at: Pos2) { + harness.hover_at(at); + harness.event(Event::PointerButton { pos: at, button, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// Drag with `button` from `from` by `by` in a few moves while `modifiers` are held +fn drag(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2, by: egui::Vec2, modifiers: Modifiers) { + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(from); + harness.event(Event::PointerButton { pos: from, button, pressed: true, modifiers }); + harness.run_steps(2); + for step in 1..=4 { + harness.hover_at(from + by * (step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(Event::PointerButton { pos: from + by, button, pressed: false, modifiers }); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(3); +} + +#[test] +fn a_right_click_opens_the_popup_at_the_cursor_in_both_views() { + let mut harness = harness(); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + assert!(matches!(harness.state().properties_popup, Some(PropertiesPopup::Open { at, .. }) if at == center)); + + harness.key_press(Key::Escape); + harness.run_steps(2); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(2); + click(&mut harness, PointerButton::Secondary, center); + assert!(is_open(&harness), "the 2D view opens it too"); +} + +#[test] +fn right_drags_keep_their_gestures_and_never_open_it() { + let mut harness = harness(); + let center = view_center(&harness); + let yaw = harness.state().session.camera.yaw; + drag(&mut harness, PointerButton::Secondary, center, vec2(80.0, -40.0), Modifiers::NONE); + assert_ne!(harness.state().session.camera.yaw, yaw, "a right drag orbits"); + assert!(!is_open(&harness), "an orbit doesn't open it"); + + let size = harness.state().session.tool.brush.size; + drag(&mut harness, PointerButton::Secondary, center, vec2(80.0, -40.0), Modifiers::COMMAND); + assert!(harness.state().session.tool.brush.size > size, "Ctrl+right drag sets the brush"); + assert!(!is_open(&harness)); + + for modifiers in [Modifiers::ALT, Modifiers::SHIFT] { + drag(&mut harness, PointerButton::Secondary, center, vec2(80.0, -40.0), modifiers); + assert!(!is_open(&harness), "{modifiers:?}"); + } +} + +#[test] +fn a_click_outside_closes_it_without_painting() { + let mut harness = harness(); + let center = view_center(&harness); + let outside = harness.state().viewport_rect.left_center() + vec2(20.0, 0.0); + let history = harness.state().session.history_labels().len(); + click(&mut harness, PointerButton::Secondary, center); + assert!(is_open(&harness)); + + click(&mut harness, PointerButton::Primary, outside); + assert_eq!(harness.state().properties_popup, None); + assert_eq!(harness.state().session.history_labels().len(), history, "the closing click doesn't paint"); + + click(&mut harness, PointerButton::Secondary, center); + click(&mut harness, PointerButton::Secondary, outside); + assert_eq!(harness.state().properties_popup, None, "a right click outside closes it and doesn't reopen it"); +} + +#[test] +fn escape_closes_it() { + let mut harness = harness(); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + assert!(is_open(&harness)); + harness.key_press(Key::Escape); + harness.run_steps(2); + assert_eq!(harness.state().properties_popup, None); +} + +#[test] +fn dragging_its_size_slider_changes_the_brush() { + let mut harness = harness(); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); + + // The Size section's header sits above its slider of the same name + let slider_label = harness + .query_all_by_label("Size") + .map(|node| node.rect()) + .filter(|rect| popup.contains_rect(*rect)) + .max_by(|first, second| first.top().total_cmp(&second.top())) + .unwrap(); + let track_y = slider_label.bottom() + 10.0; + let size = harness.state().session.tool.brush.size; + harness.drag_at(egui::pos2(slider_label.left() + 20.0, track_y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(popup.right() - 30.0, track_y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(popup.right() - 30.0, track_y)); + harness.run_steps(3); + assert!(harness.state().session.tool.brush.size > size, "{size} -> {}", harness.state().session.tool.brush.size); + assert!(is_open(&harness), "editing it keeps it open"); +} + +#[test] +fn it_shows_what_the_properties_panel_shows() { + let mut harness = harness(); + let fill = harness.state().session.doc.project.layers.values().find(|layer| matches!(layer.kind, LayerKind::Fill(_))).map(|layer| layer.id.0).unwrap(); + let selected = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": fill})); + assert!(selected.is_ok(), "{selected:?}"); + harness.run_steps(3); + + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); + let in_popup = |label: &str| harness.query_all_by_label(label).any(|node| popup.contains_rect(node.rect())); + assert!(in_popup("Projection"), "a selected fill shows its fill settings"); + assert!(!in_popup("Minimum size (%)"), "not the brush's"); +} + +#[test] +fn bake_and_render_modes_never_open_it() { + let mut harness = harness(); + let center = view_center(&harness); + for mode in [Mode::Baking, Mode::Rendering] { + harness.state_mut().ui.mode = mode; + harness.run_steps(3); + click(&mut harness, PointerButton::Secondary, center); + assert_eq!(harness.state().properties_popup, None, "{mode:?}"); + } +} From 3b302b88dc9d44235bbccb4cdd6721212a0760ba Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 05:03:21 +0000 Subject: [PATCH 31/73] Polygon fill: box selection, polygon mode, hit-test, visible polygons only and the 2D view A drag in the 3D or 2D view draws a rectangle and fills what it selects live; releasing it records one undo step. A click still fills one target, now also in the 2D view. Fill modes gain Polygon (the source quad or n-gon, from the importer's diagonals), and Mesh fills connected geometry. The hit-test picks polygons the rectangle touches or whose center it holds; visible polygons only uses a nearest-triangle buffer next to the eye-depth raster, leaving hidden texture sets out. Polygon fill's properties show its own settings and, by selection, the material, the mask gray, or why it can't fill. Wireframes show while the tool is active without changing the saved toggles. Commands: tool.fillMode takes polygon, tool.fillSelection sets hitTest and visibleOnly, and tool.click takes a screen box, a UV point or a UV box. --- crates/engine/src/fill_hit_test.rs | 80 ++++ crates/engine/src/lib.rs | 5 + crates/engine/src/painting.rs | 130 ++----- crates/engine/src/polygon_fill.rs | 470 ++++++++++++++++++++++++ crates/engine/src/polygon_fill_drag.rs | 28 ++ crates/engine/src/session.rs | 19 +- crates/engine/src/tool_cmds.rs | 71 +++- crates/engine/src/triangle_partition.rs | 77 ++++ crates/engine/tests/session.rs | 23 ++ crates/paint/src/visibility.rs | 135 ++++--- crates/ui-egui/src/dock.rs | 183 +++++++-- crates/ui-egui/src/i18n/ar.rs | 20 + crates/ui-egui/src/i18n/de.rs | 23 ++ crates/ui-egui/src/i18n/es.rs | 26 ++ crates/ui-egui/src/i18n/fr.rs | 26 ++ crates/ui-egui/src/i18n/it.rs | 26 ++ crates/ui-egui/src/i18n/ja.rs | 26 ++ crates/ui-egui/src/i18n/ko.rs | 23 ++ crates/ui-egui/src/i18n/pt_br.rs | 26 ++ crates/ui-egui/src/i18n/zh_hans.rs | 17 + crates/ui-egui/src/toolbar.rs | 31 +- crates/ui-egui/src/viewport.rs | 74 +++- crates/ui-egui/tests/polygon_fill.rs | 85 +++++ 23 files changed, 1414 insertions(+), 210 deletions(-) create mode 100644 crates/engine/src/fill_hit_test.rs create mode 100644 crates/engine/src/polygon_fill.rs create mode 100644 crates/engine/src/polygon_fill_drag.rs create mode 100644 crates/engine/src/triangle_partition.rs create mode 100644 crates/ui-egui/tests/polygon_fill.rs diff --git a/crates/engine/src/fill_hit_test.rs b/crates/engine/src/fill_hit_test.rs new file mode 100644 index 00000000..8a2b9359 --- /dev/null +++ b/crates/engine/src/fill_hit_test.rs @@ -0,0 +1,80 @@ +//! Which polygons a polygon fill box selects. + +use serde::{Deserialize, Serialize}; +use texturecraft_geom::glam::Vec2; + +/// How a polygon fill box decides whether it selects a polygon +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum FillHitTest { + /// Any part of the polygon inside the box or crossing it + #[default] + Intersection, + /// The polygon's center point inside the box + ContainedCenter, +} + +impl FillHitTest { + /// Whether the box from `low` to `high` selects the polygon made of `triangles` (their corners) + pub fn selects(self, triangles: &[[Vec2; 3]], low: Vec2, high: Vec2) -> bool { + match self { + FillHitTest::Intersection => triangles.iter().any(|corners| triangle_overlaps_box(*corners, low, high)), + FillHitTest::ContainedCenter => center(triangles).is_some_and(|point| point.cmpge(low).all() && point.cmple(high).all()), + } + } +} + +/// Area-weighted center of the triangles (their corners' mean when they have no area) +fn center(triangles: &[[Vec2; 3]]) -> Option { + let area = |corners: &[Vec2; 3]| (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs(); + let centroid = |corners: &[Vec2; 3]| (corners[0] + corners[1] + corners[2]) / 3.0; + let total: f32 = triangles.iter().map(area).sum(); + let weighted: Vec2 = triangles.iter().map(|corners| centroid(corners) * area(corners)).sum(); + let centroids: Vec2 = triangles.iter().map(centroid).sum(); + + match triangles.len() { + 0 => None, + count if total <= f32::EPSILON => Some(centroids / count as f32), + _ => Some(weighted / total), + } +} + +/// Separating axis test of a triangle against an axis-aligned box +fn triangle_overlaps_box(corners: [Vec2; 3], low: Vec2, high: Vec2) -> bool { + let triangle_low = corners[0].min(corners[1]).min(corners[2]); + let triangle_high = corners[0].max(corners[1]).max(corners[2]); + if triangle_high.cmplt(low).any() || triangle_low.cmpgt(high).any() { + return false; + } + + let box_corners = [low, Vec2::new(high.x, low.y), high, Vec2::new(low.x, high.y)]; + (0..3).all(|edge| { + let axis = (corners[(edge + 1) % 3] - corners[edge]).perp(); + let span = |points: &[Vec2]| points.iter().fold((f32::MAX, f32::MIN), |(min, max), point| (min.min(axis.dot(*point)), max.max(axis.dot(*point)))); + let (triangle_min, triangle_max) = span(&corners); + let (box_min, box_max) = span(&box_corners); + triangle_max >= box_min && box_max >= triangle_min + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const TRIANGLE: [Vec2; 3] = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 4.0)]; + + #[test] + fn intersection_needs_any_overlap_and_contained_center_the_center() { + let (low, high) = (Vec2::new(2.0, 2.0), Vec2::new(6.0, 6.0)); + assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(1.0, 1.0), high), "a box cutting the triangle"); + assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(3.0, 3.0), Vec2::new(5.0, 5.0)), "inside the bounds, past the long edge"); + assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], low, high), "the center (4/3, 4/3) lies outside"); + assert!(FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(2.0))); + } + + #[test] + fn a_polygon_center_weighs_its_triangles_by_area() { + let square = [[Vec2::ZERO, Vec2::new(2.0, 0.0), Vec2::new(2.0, 2.0)], [Vec2::ZERO, Vec2::new(2.0, 2.0), Vec2::new(0.0, 2.0)]]; + assert_eq!(center(&square), Some(Vec2::ONE)); + assert_eq!(center(&[]), None); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..824ccf48 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -15,6 +15,7 @@ pub mod commands; pub mod decal_cmds; pub mod effect_clipboard; pub mod file_cmds; +pub mod fill_hit_test; pub mod filter_lib; pub mod inspect; pub mod instance_cmds; @@ -31,6 +32,8 @@ pub mod materialx_cmds; pub mod meshmap_cmds; pub mod painting; pub mod path_tool; +mod polygon_fill; +mod polygon_fill_drag; // Mesh reimport reads files: native only. #[cfg(not(target_arch = "wasm32"))] mod preserve; @@ -45,11 +48,13 @@ pub mod smart_masks; pub mod template_cmds; pub mod text_cmds; pub mod tool_cmds; +mod triangle_partition; pub mod uv_tile_cmds; pub mod view_cmds; pub use bake::{BakeMesh, BakeMeshes, BakeTask}; pub use commands::{CommandSpec, command_specs, execute, find}; +pub use fill_hit_test::FillHitTest; pub use path_tool::PathState; pub use project_cmds::sample_session; pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 6f2a74ff..86761f79 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -7,11 +7,11 @@ use texturecraft_compose::PaintTarget; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground}; use texturecraft_geom::glam::Vec2; use texturecraft_paint::{ - CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, - fill_triangles, pick, rasterize, + CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, pick, + rasterize, }; -use crate::session::{ActiveStroke, CloneFrom, FillMode, Session, StackTarget, Tool}; +use crate::session::{ActiveStroke, CloneFrom, Session, StackTarget, Tool}; use crate::{EngineError, Result}; impl Session { @@ -301,12 +301,15 @@ impl Session { Ok(self.continue_stroke(screen, pressure)) } - /// Start a stroke in the 2D view at texture coordinate `uv`. + /// Start a stroke in the 2D view at texture coordinate `uv` (polygon fill fills there). pub fn begin_stroke_uv(&mut self, uv: Vec2, pressure: f32) -> Result<()> { self.cancel_stroke(); - if matches!(self.tool.tool, Tool::PolygonFill | Tool::ColorPicker | Tool::GeometryMask) { - return Err(EngineError::Other("use this tool in the 3D view".into())); + match self.tool.tool { + Tool::PolygonFill => return self.polygon_fill_uv(uv).map(|_| ()), + Tool::ColorPicker | Tool::GeometryMask => return Err(EngineError::Other("use this tool in the 3D view".into())), + _ => {} } + self.start_stroke(self.viewport, true, Some(uv))?; self.continue_stroke_uv(uv, pressure); Ok(()) @@ -482,21 +485,6 @@ impl Session { Ok(tiles) } - /// Polygon fill: fill the triangle / UV island / whole mesh under `screen`. - pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { - let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; - let ts = self.ts(); - let material = self.doc.project.texture_set(ts)?.material; - if hit.material != material { - return Err(EngineError::Other("that surface belongs to another texture set".into())); - } - let tris = self.fill_set(hit.tri, material); - let (gbuf, mut canvas) = self.fill_canvas(ts)?; - fill_triangles(&mut canvas, &gbuf, &tris); - self.commit_fill("Polygon fill", ts, &canvas)?; - Ok(tris.len()) - } - /// The G-buffer of texture set `ts` and an empty canvas for a one-shot fill, limited by the /// quick mask unless the fill edits it. pub(crate) fn fill_canvas(&self, ts: usize) -> Result<(std::sync::Arc, StrokeCanvas)> { @@ -510,61 +498,30 @@ impl Session { /// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask. pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas) -> Result<()> { - let size = (canvas.alpha.width(), canvas.alpha.height()); - let src = |opacity| CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None }; if self.quick_mask.editing { - self.commit_quick_mask(ts, size, src(self.tool.brush.opacity)); - return Ok(()); + return self.paint_fill(ts, canvas); } - self.edit(label, |s| { - let target = s.paint_target()?; - let values = s.stroke_values(target); - match target { - PaintTarget::Layer(id) => commit_layer(&mut s.doc.pixels, id, size, &values, src(s.tool.brush.opacity), &mut Staging::default()), - PaintTarget::Mask(eid) => commit_mask(&mut s.doc.pixels, eid, size, s.tool.mask_value, src(s.tool.brush.opacity), &mut Staging::default()), - } - Ok(()) - }) + + self.edit(label, |session| session.paint_fill(ts, canvas)) } - /// Triangles filled by the current fill mode starting from `tri`. - fn fill_set(&self, tri: u32, material: usize) -> BTreeSet { - let m = &self.mesh; - match self.tool.fill_mode { - FillMode::Triangle => [tri].into_iter().collect(), - FillMode::Mesh => m.triangles_of(material).map(|t| t as u32).collect(), - FillMode::UvIsland => { - // Triangles sharing an edge in UV space form a UV island: imported meshes often - // split vertices along hard edges (or per face) where the UVs run on, so shared - // vertex indices alone break an island into its polygons. - let corner = |i: usize| m.uvs.get(i).map(|uv| [(uv.x * 1e5).round() as i64, (uv.y * 1e5).round() as i64]); - let edges = |t: usize| match m.tri(t).map(|v| v.map(corner)) { - Some([Some(a), Some(b), Some(c)]) => [(a, b), (b, c), (c, a)].map(|(p, q)| (p.min(q), p.max(q))).to_vec(), - _ => Vec::new(), - }; - let mut by_edge: BTreeMap<_, Vec> = BTreeMap::new(); - for t in m.triangles_of(material) { - for e in edges(t) { - by_edge.entry(e).or_default().push(t as u32); - } - } - let mut seen = BTreeSet::new(); - let mut stack = vec![tri]; - while let Some(t) = stack.pop() { - if !seen.insert(t) { - continue; - } - for e in edges(t as usize) { - for n in by_edge.get(&e).map(Vec::as_slice).unwrap_or(&[]) { - if !seen.contains(n) { - stack.push(*n); - } - } - } - } - seen - } + /// Paint a one-shot fill with the tool's material into the paint target, or into the quick mask while it is edited (no undo step) + pub(crate) fn paint_fill(&mut self, ts: usize, canvas: &StrokeCanvas) -> Result<()> { + let size = (canvas.alpha.width(), canvas.alpha.height()); + let opacity = self.tool.brush.opacity; + let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None }; + if self.quick_mask.editing { + self.commit_quick_mask(ts, size, source); + return Ok(()); } + + let target = self.paint_target()?; + let values = self.stroke_values(target); + match target { + PaintTarget::Layer(id) => commit_layer(&mut self.doc.pixels, id, size, &values, source, &mut Staging::default()), + PaintTarget::Mask(effect) => commit_mask(&mut self.doc.pixels, effect, size, self.tool.mask_value, source, &mut Staging::default()), + } + Ok(()) } /// Color picker: copy the material under the cursor into the tool's paint values. @@ -627,34 +584,3 @@ fn with_commit_source( let carried = st.canvas.pickup.as_ref().map(|p| &p.values); f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried }) } - -#[cfg(test)] -mod tests { - use texturecraft_geom::glam::{Vec2, Vec3}; - use texturecraft_geom::mesh::Mesh; - use texturecraft_geom::primitives; - - use crate::session::{FillMode, Session}; - - #[test] - fn uv_island_fill_follows_uvs_across_split_vertices() { - // Two copies of a plane, each triangle with its own three vertices (as hard edges or - // per-face imports leave a mesh), the second copy apart in UV space. - let plane = primitives::plane(2.0, 4); - let (mut positions, mut uvs) = (Vec::::new(), Vec::::new()); - for shift in [0.0, 0.5] { - for i in plane.indices.iter().map(|i| *i as usize) { - positions.push(plane.positions[i] + Vec3::Y * shift); - uvs.push(plane.uvs[i] * 0.5 + shift); - } - } - let indices = (0..positions.len() as u32).collect(); - let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap(); - let n = plane.triangle_count(); - assert_eq!(mesh.vertex_count(), 6 * n, "no vertex is shared"); - let mut s = Session::new_project("t", mesh, "test", None, 128).unwrap(); - s.tool.fill_mode = FillMode::UvIsland; - assert_eq!(s.fill_set(0, 0).len(), n, "the whole first island"); - assert_eq!(s.fill_set(n as u32, 0).len(), n, "only the second island"); - } -} diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs new file mode 100644 index 00000000..2d577835 --- /dev/null +++ b/crates/engine/src/polygon_fill.rs @@ -0,0 +1,470 @@ +//! Polygon fill: fill the triangles, polygons, UV islands or connected meshes under a click or inside a dragged box, in either view. + +use std::borrow::Cow; +use std::collections::{BTreeSet, HashSet}; + +use texturecraft_geom::glam::{Vec2, Vec4Swizzles}; +use texturecraft_geom::{Mesh, NO_TRI}; +use texturecraft_paint::{EyeDepth, fill_triangles}; + +use crate::polygon_fill_drag::PolygonFillDrag; +use crate::session::{FillMode, Session}; +use crate::triangle_partition::TrianglePartition; +use crate::{EngineError, Result}; + +/// Corners closer than one step of this grid (per unit of position or UV) count as the same corner +const CORNER_GRID_STEPS: f32 = 1e5; + +/// Clip-space w below which a vertex counts as behind the camera +const MIN_CLIP_W: f32 = 1e-5; + +impl Session { + /// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen` + pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { + let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; + if hit.material != self.fill_material()? { + return Err(EngineError::Other("that surface belongs to another texture set".into())); + } + + self.fill_group_of(hit.tri) + } + + /// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view) + pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result { + let material = self.fill_material()?; + let mesh = &self.mesh; + let triangle = mesh + .triangles_of(material) + .find(|triangle| uv_corners(mesh, *triangle).is_some_and(|corners| contains(corners, uv))) + .ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; + + self.fill_group_of(triangle as u32) + } + + /// Fill what the box between viewport pixels `corner` and `opposite` selects (one undo step) + pub fn polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result { + self.drag_polygon_fill_box(corner, opposite, viewport)?; + Ok(self.end_polygon_fill_box()) + } + + /// Fill what the box between texture coordinates `corner` and `opposite` selects (the 2D view, one undo step) + pub fn polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result { + self.drag_polygon_fill_box_uv(corner, opposite)?; + Ok(self.end_polygon_fill_box()) + } + + /// Show the fill of a box being dragged between viewport pixels `corner` and `opposite` + pub fn drag_polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result { + let (low, high) = box_bounds(corner, opposite)?; + let viewport = viewport.max(Vec2::ONE); + self.start_polygon_fill_drag(Some(viewport))?; + + let view_proj = self.camera.view_proj(viewport.x / viewport.y); + let mesh = self.mesh.clone(); + let to_screen = |vertex: usize| { + let clip = view_proj * mesh.positions.get(vertex)?.extend(1.0); + let ndc = (clip.w > MIN_CLIP_W).then(|| clip.xy() / clip.w)?; + Some(Vec2::new(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * viewport) + }; + let screen_corners = |triangle: usize| { + let [first, second, third] = mesh.tri(triangle)?; + Some([to_screen(first)?, to_screen(second)?, to_screen(third)?]) + }; + let selected = self.box_selection(&screen_corners, low, high); + self.show_box_fill(selected) + } + + /// Show the fill of a box being dragged between texture coordinates `corner` and `opposite` (the 2D view) + pub fn drag_polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result { + let (low, high) = box_bounds(corner, opposite)?; + self.start_polygon_fill_drag(None)?; + + let mesh = self.mesh.clone(); + let selected = self.box_selection(&|triangle| uv_corners(&mesh, triangle), low, high); + self.show_box_fill(selected) + } + + /// Finish the dragged box: what it filled becomes one undo step. Returns the filled triangle count + pub fn end_polygon_fill_box(&mut self) -> usize { + let Some(drag) = self.polygon_fill_drag.take() else { return 0 }; + + // Quick mask edits keep no history, as with its strokes + let filled = drag.filled.len(); + if filled > 0 && drag.quick_mask_before.is_none() { + self.push_history("Polygon fill", drag.before); + } + filled + } + + /// The mesh material of the texture set being painted + fn fill_material(&self) -> Result { + Ok(self.doc.project.texture_set(self.ts())?.material) + } + + /// The triangles the current fill mode fills together, for `material` + fn fill_partition(&self, material: usize) -> TrianglePartition { + match self.tool.fill_mode { + FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::::new()), + FillMode::Polygon => TrianglePartition::new(&self.mesh, material, polygon_edges), + FillMode::UvIsland => TrianglePartition::new(&self.mesh, material, uv_edges), + FillMode::Mesh => TrianglePartition::new(&self.mesh, material, position_edges), + } + } + + /// Fill the fill-mode group holding `triangle` (one undo step) + fn fill_group_of(&mut self, triangle: u32) -> Result { + let ts = self.ts(); + let groups = self.fill_partition(self.fill_material()?); + let triangles: BTreeSet = groups.group(triangle).unwrap_or_default().iter().copied().collect(); + + let (gbuf, mut canvas) = self.fill_canvas(ts)?; + fill_triangles(&mut canvas, &gbuf, &triangles); + self.commit_fill("Polygon fill", ts, &canvas)?; + Ok(triangles.len()) + } + + /// Begin a box drag unless one is under way; `viewport` is the 3D view's size (None in the 2D view) + fn start_polygon_fill_drag(&mut self, viewport: Option) -> Result<()> { + if self.polygon_fill_drag.is_some() { + return Ok(()); + } + + let material = self.fill_material()?; + let polygons = match self.tool.fill_mode { + FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::::new()), + _ => TrianglePartition::new(&self.mesh, material, polygon_edges), + }; + let depth = viewport + .filter(|_| self.tool.fill_visible_only) + .map(|size| (EyeDepth::render(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32), size)); + self.polygon_fill_drag = Some(PolygonFillDrag { + before: self.doc.clone(), + quick_mask_before: self.quick_mask.editing.then(|| self.quick_mask.masks.clone()), + filled: BTreeSet::new(), + depth, + polygons, + fill_groups: self.fill_partition(material), + failed: false, + }); + Ok(()) + } + + /// The mesh as the 3D view shows it: hidden texture sets' triangles collapse to a point, so nothing behind them counts as hidden + fn shown_mesh(&self) -> Cow<'_, Mesh> { + let sets = &self.doc.project.texture_sets; + if sets.iter().all(|set| set.visible) { + return Cow::Borrowed(&self.mesh); + } + + let mut mesh = (*self.mesh).clone(); + for set in sets.iter().filter(|set| !set.visible) { + for triangle in self.mesh.triangles_of(set.material) { + if let Some(corners) = mesh.indices.get_mut(triangle * 3..triangle * 3 + 3) { + let first = corners[0]; + corners.fill(first); + } + } + } + Cow::Owned(mesh) + } + + /// Triangles the dragged box from `low` to `high` fills, given each triangle's `corners` in the box's space + fn box_selection(&self, corners: &dyn Fn(usize) -> Option<[Vec2; 3]>, low: Vec2, high: Vec2) -> BTreeSet { + let Some(drag) = &self.polygon_fill_drag else { return BTreeSet::new() }; + + let visible = drag.depth.as_ref().map(|(depth, viewport)| visible_triangles(depth, *viewport, low, high)); + let hit_test = self.tool.fill_hit_test; + let mut groups = BTreeSet::new(); + for polygon in &drag.polygons.groups { + let seen = visible.as_ref().is_none_or(|visible| polygon.iter().any(|triangle| visible.contains(triangle))); + let triangles: Option> = polygon.iter().map(|triangle| corners(*triangle as usize)).collect(); + if seen && triangles.is_some_and(|triangles| hit_test.selects(&triangles, low, high)) { + groups.extend(polygon.iter().filter_map(|triangle| drag.fill_groups.index_of(*triangle))); + } + } + + groups.iter().filter_map(|group| drag.fill_groups.groups.get(*group)).flatten().copied().collect() + } + + /// Show the box drag's fill of `selected`: the document before the drag, refilled when the selection changed + fn show_box_fill(&mut self, selected: BTreeSet) -> Result { + let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) }; + if drag.failed || drag.filled == selected { + return Ok(drag.filled.len()); + } + + drag.filled = selected.clone(); + let previous = std::mem::replace(&mut self.doc, drag.before.clone()); + if let Some(masks) = &drag.quick_mask_before { + self.quick_mask.masks = masks.clone(); + } + + let ts = self.ts(); + let painted = if selected.is_empty() { + Ok(()) + } else { + self.fill_canvas(ts).and_then(|(gbuf, mut canvas)| { + fill_triangles(&mut canvas, &gbuf, &selected); + self.paint_fill(ts, &canvas) + }) + }; + self.invalidate_changed(&previous); + self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); + + // A failed fill is reported once; the rest of the drag fills nothing + if painted.is_err() + && let Some(mut drag) = self.polygon_fill_drag.take() + { + self.restore_before_box(&drag); + drag.failed = true; + drag.filled.clear(); + self.polygon_fill_drag = Some(drag); + } + painted.map(|_| selected.len()) + } + + /// Put back the document and quick mask from before the box `drag` + fn restore_before_box(&mut self, drag: &PolygonFillDrag) { + let previous = std::mem::replace(&mut self.doc, drag.before.clone()); + if let Some(masks) = &drag.quick_mask_before { + self.quick_mask.masks = masks.clone(); + self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); + } + self.invalidate_changed(&previous); + } +} + +/// Triangles `depth` (rendered for `viewport`) shows in the viewport pixels from `low` to `high` +fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> HashSet { + let pixels_per_point = Vec2::new(depth.width as f32, depth.height as f32) / viewport; + let (first, last) = ((low * pixels_per_point).floor(), (high * pixels_per_point).ceil()); + let columns = first.x.max(0.0) as usize..(last.x as usize).min(depth.width as usize); + let rows = first.y.max(0.0) as usize..(last.y as usize).min(depth.height as usize); + + rows.flat_map(|row| depth.triangle.get(row * depth.width as usize..).into_iter().flat_map(|pixels| pixels.iter().take(columns.end).skip(columns.start))) + .copied() + .filter(|triangle| *triangle != NO_TRI) + .collect() +} + +/// The two corners spanning a box, lowest first +fn box_bounds(corner: Vec2, opposite: Vec2) -> Result<(Vec2, Vec2)> { + if !corner.is_finite() || !opposite.is_finite() { + return Err(EngineError::Other("the box corners must be finite".into())); + } + + Ok((corner.min(opposite), corner.max(opposite))) +} + +/// Texture coordinates of `triangle`'s corners +fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> { + let [first, second, third] = mesh.tri(triangle)?; + Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?]) +} + +/// Whether `point` lies in the triangle with `corners` (either winding) +fn contains(corners: [Vec2; 3], point: Vec2) -> bool { + let side = |edge: usize| (corners[(edge + 1) % 3] - corners[edge]).perp_dot(point - corners[edge]); + let sides = [side(0), side(1), side(2)]; + sides.iter().all(|side| *side >= 0.0) || sides.iter().all(|side| *side <= 0.0) +} + +/// The polygon diagonals of `triangle`: edges the importer added to split a polygon +fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> { + let hidden = mesh.diagonals.get(triangle).copied().unwrap_or(0); + let Some(vertices) = mesh.indices.get(triangle * 3..triangle * 3 + 3) else { return Vec::new() }; + + (0..3) + .filter(|edge| hidden >> edge & 1 == 1) + .map(|edge| { + let (from, to) = (vertices[edge], vertices[(edge + 1) % 3]); + (from.min(to), from.max(to)) + }) + .collect() +} + +/// `triangle`'s edges in UV space: imports often split vertices along hard edges where the UVs run on, so vertex indices alone break islands apart +fn uv_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 2], [i64; 2])> { + let corner = |uv: Vec2| (uv * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64); + let Some([first, second, third]) = uv_corners(mesh, triangle).map(|uvs| uvs.map(corner)) else { return Vec::new() }; + + [(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec() +} + +/// `triangle`'s edges by position: UV seams and hard edges split vertices but leave the geometry connected +fn position_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 3], [i64; 3])> { + let corner = |vertex: usize| mesh.positions.get(vertex).map(|position| (*position * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64)); + let Some([first, second, third]) = mesh.tri(triangle) else { return Vec::new() }; + let (Some(first), Some(second), Some(third)) = (corner(first), corner(second), corner(third)) else { return Vec::new() }; + + [(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec() +} + +#[cfg(test)] +mod tests { + use texturecraft_core::Channel; + use texturecraft_geom::glam::{Vec2, Vec3}; + use texturecraft_geom::mesh::Mesh; + use texturecraft_geom::primitives; + + use crate::fill_hit_test::FillHitTest; + use crate::session::{FillMode, Session, Tool}; + + /// The roughness the test fills paint, to tell filled texels apart + const FILL_ROUGHNESS: f32 = 0.9; + + /// A polygon fill session on `mesh` painting roughness [`FILL_ROUGHNESS`] + fn fill_session(mesh: Mesh) -> Session { + let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap(); + session.viewport = Vec2::new(400.0, 400.0); + session.tool.tool = Tool::PolygonFill; + session.tool.values.insert(Channel::Roughness, [FILL_ROUGHNESS; 3]); + session.update(); + session + } + + /// Whether the texel at texture coordinate `uv` shows the fill's roughness + fn filled_at(session: &Session, uv: Vec2) -> bool { + let (width, height) = session.caches[0].size; + let roughness = session.caches[0].composite.value(Channel::Roughness, (uv.x * width as f32) as u32, (uv.y * height as f32) as u32); + (roughness[0] - FILL_ROUGHNESS).abs() < 0.01 + } + + /// Two copies of a plane apart in space and in UV space, each triangle with its own three vertices (as hard edges or per-face imports leave a mesh) + fn split_planes() -> (Mesh, usize) { + let plane = primitives::plane(2.0, 4); + let (mut positions, mut uvs) = (Vec::::new(), Vec::::new()); + for shift in [0.0, 0.5] { + for vertex in plane.indices.iter().map(|index| *index as usize) { + positions.push(plane.positions[vertex] + Vec3::Y * shift); + uvs.push(plane.uvs[vertex] * 0.5 + shift); + } + } + let indices = (0..positions.len() as u32).collect(); + let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap(); + assert_eq!(mesh.vertex_count(), 6 * plane.triangle_count(), "no vertex is shared"); + (mesh, plane.triangle_count()) + } + + #[test] + fn uv_island_and_mesh_fills_follow_seams_split_vertices_leave_apart() { + let (mesh, per_plane) = split_planes(); + let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap(); + + for fill_mode in [FillMode::UvIsland, FillMode::Mesh] { + session.tool.fill_mode = fill_mode; + let groups = session.fill_partition(0); + assert_eq!(groups.group(0).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: the whole first plane"); + assert_eq!(groups.group(per_plane as u32).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: only the second plane"); + } + } + + #[test] + fn polygon_mode_groups_the_two_triangles_of_each_quad() { + let mut session = fill_session(primitives::plane(2.0, 2)); + + session.tool.fill_mode = FillMode::Triangle; + assert_eq!(session.fill_partition(0).group(0), Some(&[0][..])); + + session.tool.fill_mode = FillMode::Polygon; + let mut quad = session.fill_partition(0).group(0).unwrap().to_vec(); + quad.sort_unstable(); + assert_eq!(quad, [0, 1], "the quad's two triangles and no other quad"); + } + + #[test] + fn a_uv_box_over_half_a_plane_fills_that_half() { + let mut session = fill_session(primitives::plane(2.0, 4)); + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + + let filled = session.polygon_fill_box_uv(Vec2::new(-0.01, -0.01), Vec2::new(0.5, 1.01)).unwrap(); + session.update(); + + assert_eq!(filled, 16, "the left two columns of quads"); + assert!(filled_at(&session, Vec2::new(0.1, 0.5)) && filled_at(&session, Vec2::new(0.45, 0.9))); + assert!(!filled_at(&session, Vec2::new(0.55, 0.5)) && !filled_at(&session, Vec2::new(0.9, 0.1))); + } + + #[test] + fn intersection_and_contained_center_differ_on_a_box_missing_a_quads_center() { + let mut session = fill_session(primitives::plane(2.0, 2)); + session.tool.fill_mode = FillMode::Polygon; + let (corner, opposite) = (Vec2::new(0.0, 0.0), Vec2::new(0.2, 0.2)); + + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 0, "the quad's center (0.25, 0.25) is outside"); + assert_ne!(session.undo_label(), Some("Polygon fill"), "an empty box records no undo step"); + + session.tool.fill_hit_test = FillHitTest::Intersection; + assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 2, "the quad the box cuts"); + } + + #[test] + fn visible_only_skips_the_back_of_a_cube() { + let mut session = fill_session(primitives::cube(1.0)); + session.camera.yaw = 0.6; + session.camera.pitch = 0.4; + let (low, high) = (Vec2::ZERO, session.viewport); + let every_triangle = session.mesh.triangle_count(); + + session.tool.fill_visible_only = true; + assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle / 2, "the three sides the camera sees"); + + session.tool.fill_visible_only = false; + assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle); + } + + #[test] + fn visible_only_sees_through_a_hidden_texture_set() { + let mut session = fill_session(primitives::material_ball()); + let base = session.doc.project.texture_sets.iter().position(|set| set.name == "Base").unwrap(); + session.active_set = base; + let (low, high) = (Vec2::ZERO, session.viewport); + + let behind_the_ball = session.polygon_fill_box(low, high, session.viewport).unwrap(); + session.doc.project.texture_sets[0].visible = false; + let ball_hidden = session.polygon_fill_box(low, high, session.viewport).unwrap(); + + assert!(ball_hidden > behind_the_ball, "hiding the ball shows more of the base: {ball_hidden} vs {behind_the_ball}"); + } + + #[test] + fn a_dragged_box_fills_live_and_records_one_step_when_it_ends() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let history = session.history_labels().len(); + + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap(), 16, "shrinking the box unfills"); + session.update(); + assert!(filled_at(&session, Vec2::new(0.2, 0.5)) && !filled_at(&session, Vec2::new(0.8, 0.5)), "the fill shows while dragging"); + assert_eq!(session.history_labels().len(), history, "no undo step yet"); + + assert_eq!(session.end_polygon_fill_box(), 16); + assert_eq!(session.history_labels().len(), history + 1); + session.undo().unwrap(); + session.update(); + assert!(!filled_at(&session, Vec2::new(0.2, 0.5)), "one undo removes the whole drag"); + } + + #[test] + fn a_uv_box_over_the_second_uv_tile_fills_that_tile_only() { + let mut session = fill_session(primitives::udim_plane()); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]); + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + + let every_triangle = session.mesh.triangle_count(); + assert_eq!(session.polygon_fill_box_uv(Vec2::new(0.5, 0.0), Vec2::ONE).unwrap(), every_triangle / 2, "the atlas's right half is tile 1002"); + } + + #[test] + fn a_2d_click_fills_the_triangle_under_it() { + let mut session = fill_session(primitives::plane(2.0, 1)); + + assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1); + session.update(); + + assert!(filled_at(&session, Vec2::new(0.2, 0.7))); + assert!(!filled_at(&session, Vec2::new(0.7, 0.2)), "the quad's other triangle stays"); + assert!(session.polygon_fill_uv(Vec2::new(1.5, 0.5)).is_err(), "nothing outside the UVs"); + } +} diff --git a/crates/engine/src/polygon_fill_drag.rs b/crates/engine/src/polygon_fill_drag.rs new file mode 100644 index 00000000..4a7bc104 --- /dev/null +++ b/crates/engine/src/polygon_fill_drag.rs @@ -0,0 +1,28 @@ +//! A polygon fill box being dragged: what it filled so far and what it needs to refill each move. + +use std::collections::{BTreeMap, BTreeSet}; + +use texturecraft_geom::glam::Vec2; +use texturecraft_paint::EyeDepth; +use texturecraft_texel::TileImage; + +use crate::session::Document; +use crate::triangle_partition::TrianglePartition; + +/// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends +pub(crate) struct PolygonFillDrag { + /// The document before the drag, refilled each time the selection changes + pub before: Document, + /// The quick mask's coverage before the drag, when the drag paints the quick mask + pub quick_mask_before: Option>, + /// The triangles filled so far + pub filled: BTreeSet, + /// What the camera sees and the viewport size it was rendered for (3D view, visible polygons only) + pub depth: Option<(EyeDepth, Vec2)>, + /// The polygons the box tests + pub polygons: TrianglePartition, + /// What the fill mode fills together + pub fill_groups: TrianglePartition, + /// The fill failed (reported once): the rest of the drag fills nothing + pub failed: bool, +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 36263560..c5b55649 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -165,6 +165,8 @@ impl ViewMode { pub enum FillMode { #[default] Triangle, + /// The source polygon (quad or n-gon) the importer split into triangles + Polygon, UvIsland, Mesh, } @@ -210,6 +212,12 @@ pub struct ToolState { /// Gray painted into masks. pub mask_value: f32, pub fill_mode: FillMode, + /// How a polygon fill box decides which polygons it selects + #[serde(default)] + pub fill_hit_test: crate::fill_hit_test::FillHitTest, + /// Polygon fill boxes in the 3D view select only the polygons the camera sees + #[serde(default = "default_fill_visible_only")] + pub fill_visible_only: bool, /// Stencil used by the Projection tool. #[serde(default)] pub stencil: Option, @@ -231,6 +239,10 @@ fn default_smudge_strength() -> f32 { 0.5 } +fn default_fill_visible_only() -> bool { + true +} + /// What the Clone tool copies (the clone source modes). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum CloneFrom { @@ -260,6 +272,8 @@ impl Default for ToolState { enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(), mask_value: 1.0, fill_mode: FillMode::Triangle, + fill_hit_test: Default::default(), + fill_visible_only: default_fill_visible_only(), stencil: None, smudge_strength: default_smudge_strength(), clone_source: None, @@ -356,6 +370,8 @@ pub struct Session { /// The last stroke's camera visibility buffer: reused while the camera, view size and mesh /// are unchanged, so back-to-back dabs start instantly. pub(crate) depth_cache: Option, + /// The polygon fill box being dragged + pub(crate) polygon_fill_drag: Option, /// The user's export presets (kept when another project opens). pub export_presets: crate::preset_cmds::UserPresets, /// The user's project templates (kept when another project opens). @@ -405,6 +421,7 @@ impl Session { revision: 1, log: Vec::new(), depth_cache: None, + polygon_fill_drag: None, export_presets: Default::default(), templates: Default::default(), }) @@ -530,7 +547,7 @@ impl Session { /// Mark dirty every texture set whose composite differs between `other` and the current /// document (after an edit, undo or redo). - fn invalidate_changed(&mut self, other: &Document) { + pub(crate) fn invalidate_changed(&mut self, other: &Document) { self.follow_uv_layouts(&other.project); self.sync_caches(); let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::>(); diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 7fa5fdab..ba7f0f9b 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -7,6 +7,7 @@ use texturecraft_geom::glam::Vec2; use texturecraft_paint::{Alignment, BrushAlpha, alphas}; use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp}; +use crate::fill_hit_test::FillHitTest; use crate::session::{CloneFrom, CloneSource, FillMode, Tool}; use crate::{Result, Session, cmd}; @@ -69,7 +70,16 @@ pub fn specs() -> Vec { always, clone_source ), - cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|uvIsland|mesh}", always, fill_mode), + cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|polygon|uvIsland|mesh}", always, fill_mode), + cmd!( + "tool.fillSelection", + "Polygon fill selection", + [], + None, + "{hitTest?: intersection|containedCenter (a box selects polygons it touches, or whose center it holds), visibleOnly?: bool (3D view boxes select only what the camera sees)}", + always, + fill_selection + ), cmd!("tool.stroke", "Paint stroke", [], None, "{points: [[x,y],...] viewport pixels, viewport?: [w,h]} — paints with the current tool", always, stroke), cmd!( "tool.strokeUv", @@ -80,7 +90,15 @@ pub fn specs() -> Vec { always, stroke_uv ), - cmd!("tool.click", "Tool click", [], None, "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab", always, click), + cmd!( + "tool.click", + "Tool click", + [], + None, + "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}", + always, + click + ), cmd!("tool.state", "Tool state", [], None, "{}", always, |s, _| Ok(serde_json::to_value(&s.tool).unwrap_or(Value::Null))), ] } @@ -322,6 +340,7 @@ fn clone_source(s: &mut Session, p: &Value) -> Result { fn fill_mode(s: &mut Session, p: &Value) -> Result { s.tool.fill_mode = match strp(p, "mode").unwrap_or("triangle") { "triangle" => FillMode::Triangle, + "polygon" => FillMode::Polygon, "uvIsland" | "island" => FillMode::UvIsland, "mesh" => FillMode::Mesh, other => return Err(bad("tool.fillMode", format!("unknown fill mode `{other}`"))), @@ -329,6 +348,20 @@ fn fill_mode(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +fn fill_selection(s: &mut Session, p: &Value) -> Result { + match strp(p, "hitTest") { + None => {} + Some("intersection") => s.tool.fill_hit_test = FillHitTest::Intersection, + Some("containedCenter") => s.tool.fill_hit_test = FillHitTest::ContainedCenter, + Some(other) => return Err(bad("tool.fillSelection", format!("unknown hit-test `{other}` (intersection or containedCenter)"))), + } + if let Some(visible_only) = boolp(p, "visibleOnly") { + s.tool.fill_visible_only = visible_only; + } + + Ok(Value::Null) +} + pub(crate) fn viewport_of(s: &Session, p: &Value) -> Vec2 { match p.get("viewport").and_then(Value::as_array) { Some(a) if a.len() == 2 => { @@ -370,21 +403,43 @@ fn stroke(s: &mut Session, p: &Value) -> Result { } fn click(s: &mut Session, p: &Value) -> Result { + if s.tool.tool == Tool::PolygonFill + && let Some(triangles) = polygon_fill_click(s, p)? + { + s.update(); + return Ok(json!({ "triangles": triangles })); + } + let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) }; - let vp = viewport_of(s, p); + + let point = Vec2::new(x, y); + let viewport = viewport_of(s, p); let out = match s.tool.tool { - Tool::PolygonFill => json!({ "triangles": s.polygon_fill(Vec2::new(x, y), vp)? }), + Tool::PolygonFill => json!({ "triangles": s.polygon_fill(point, viewport)? }), Tool::ColorPicker => { - let v = s.color_pick(Vec2::new(x, y), vp)?; - json!(v.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::>()) + let picked = s.color_pick(point, viewport)?; + json!(picked.iter().map(|(channel, value)| (channel.id().to_string(), json!(value))).collect::>()) } - Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, Vec2::new(x, y), vp)?, - _ => json!({ "stamps": s.stroke_points(&[Vec2::new(x, y)], vp)? }), + Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, point, viewport)?, + _ => json!({ "stamps": s.stroke_points(&[point], viewport)? }), }; s.update(); Ok(out) } +/// The polygon fill forms of `tool.click` besides a plain `{x, y}` point: None for that point +fn polygon_fill_click(s: &mut Session, p: &Value) -> Result> { + let screen_box = (f32p(p, "x0"), f32p(p, "y0"), f32p(p, "x1"), f32p(p, "y1")); + let filled = match (pair(p, "uv0"), pair(p, "uv1"), pair(p, "uv"), screen_box) { + (Some(corner), Some(opposite), ..) => s.polygon_fill_box_uv(corner.into(), opposite.into())?, + (_, _, Some(uv), _) => s.polygon_fill_uv(uv.into())?, + (.., (Some(x0), Some(y0), Some(x1), Some(y1))) => s.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(s, p))?, + _ => return Ok(None), + }; + + Ok(Some(filled)) +} + fn stroke_uv(s: &mut Session, p: &Value) -> Result { let points = points_param("tool.strokeUv", p, "points")?.ok_or_else(|| bad("tool.strokeUv", "`points` must be an array of [u, v]"))?; let tiles = s.stroke_uv_points(&points)?; diff --git a/crates/engine/src/triangle_partition.rs b/crates/engine/src/triangle_partition.rs new file mode 100644 index 00000000..1364fe69 --- /dev/null +++ b/crates/engine/src/triangle_partition.rs @@ -0,0 +1,77 @@ +//! Triangles of one material grouped into the pieces polygon fill selects and fills. + +use std::collections::{BTreeMap, HashMap}; + +use texturecraft_geom::Mesh; + +/// A material's triangles split into groups joined across shared edges +pub struct TrianglePartition { + /// The triangles of each group + pub groups: Vec>, + /// The index of each triangle's group + group_of: HashMap, +} + +impl TrianglePartition { + /// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both + pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { + let triangles: Vec = mesh.triangles_of(material).map(|triangle| triangle as u32).collect(); + let mut by_edge: BTreeMap> = BTreeMap::new(); + for &triangle in &triangles { + for edge in edges(mesh, triangle as usize) { + by_edge.entry(edge).or_default().push(triangle); + } + } + + let mut groups = Vec::new(); + let mut group_of = HashMap::with_capacity(triangles.len()); + for &start in &triangles { + if group_of.contains_key(&start) { + continue; + } + let mut members = Vec::new(); + let mut stack = vec![start]; + group_of.insert(start, groups.len()); + while let Some(triangle) = stack.pop() { + members.push(triangle); + for neighbour in edges(mesh, triangle as usize).iter().flat_map(|edge| by_edge.get(edge).into_iter().flatten()) { + if !group_of.contains_key(neighbour) { + group_of.insert(*neighbour, groups.len()); + stack.push(*neighbour); + } + } + } + groups.push(members); + } + TrianglePartition { groups, group_of } + } + + /// The index in [`TrianglePartition::groups`] of the group holding `triangle` (None for a triangle of another material) + pub fn index_of(&self, triangle: u32) -> Option { + self.group_of.get(&triangle).copied() + } + + /// The group holding `triangle` (None for a triangle of another material) + pub fn group(&self, triangle: u32) -> Option<&[u32]> { + self.index_of(triangle).and_then(|group| self.groups.get(group)).map(Vec::as_slice) + } +} + +#[cfg(test)] +mod tests { + use texturecraft_geom::primitives; + + use super::*; + + #[test] + fn triangles_sharing_a_key_join_one_group() { + let mesh = primitives::plane(2.0, 2); + let singles = TrianglePartition::new(&mesh, 0, |_, _| Vec::::new()); + let pairs = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 2]); + + assert_eq!(singles.groups.len(), mesh.triangle_count()); + assert_eq!(pairs.groups.len(), mesh.triangle_count() / 2); + assert_eq!(pairs.group(3).map(<[u32]>::len), Some(2)); + assert_eq!(pairs.group(99), None); + } +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 02be7a8d..7973d52e 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -105,6 +105,29 @@ fn polygon_fill_and_color_picker() { assert!((r["roughness"][0].as_f64().unwrap() - 0.9).abs() < 0.01, "{r}"); } +#[test] +fn polygon_fill_boxes_survive_hostile_params() { + let hostile = [ + json!({"x0": 1e30, "y0": -1e30, "x1": f64::MAX, "y1": 0, "viewport": [1e9, 1e9]}), + json!({"x0": 0, "y0": 0, "x1": 0, "y1": 0, "viewport": [16, 16]}), + json!({"uv0": [1e30, -1e30], "uv1": [0, 0]}), + json!({"uv0": [0.5], "uv1": "x", "uv": [f64::MIN, 2]}), + json!({"hitTest": "nope", "visibleOnly": "yes", "mode": 7}), + ]; + for visible_only in [true, false] { + for hit_test in ["intersection", "containedCenter"] { + let mut session = session(); + execute(&mut session, "tool.polygonFill", &Value::Null).unwrap(); + execute(&mut session, "tool.fillSelection", &json!({"hitTest": hit_test, "visibleOnly": visible_only})).unwrap(); + for params in &hostile { + let _ = execute(&mut session, "tool.click", params); + let _ = execute(&mut session, "tool.fillSelection", params); + session.update(); + } + } + } +} + /// Every command must return Ok or Err — never panic — for hostile params. #[test] fn panic_hunt() { diff --git a/crates/paint/src/visibility.rs b/crates/paint/src/visibility.rs index 01ce84f8..e914d297 100644 --- a/crates/paint/src/visibility.rs +++ b/crates/paint/src/visibility.rs @@ -3,10 +3,25 @@ use rayon::prelude::*; use texturecraft_geom::glam::{Mat4, Vec3, Vec4}; -use texturecraft_geom::{Mesh, OrbitCamera}; +use texturecraft_geom::{Mesh, NO_TRI, OrbitCamera}; const BAND: usize = 16; +/// Largest buffer side in pixels. +const MAX_SIZE: u32 = 4096; + +/// Clip-space w below which a vertex counts as behind the camera. +const MIN_CLIP_W: f32 = 1e-5; + +/// Screen area (pixels squared) below which a triangle is skipped as degenerate. +const MIN_SCREEN_AREA: f32 = 1e-9; + +/// How far outside a triangle (in barycentric weight) a pixel center may lie and still count, closing seams between neighbours. +const EDGE_TOLERANCE: f32 = 1e-4; + +/// [`EyeDepth::bias`] as a fraction of the scene radius. +const BIAS_PER_RADIUS: f32 = 0.004; + /// Distance from the eye to the nearest surface per screen pixel (f32::MAX where empty). #[derive(Clone, Debug)] pub struct EyeDepth { @@ -15,73 +30,99 @@ pub struct EyeDepth { pub view_proj: Mat4, pub eye: Vec3, pub dist: Vec, + /// The nearest triangle per screen pixel ([`NO_TRI`] where empty). + pub triangle: Vec, /// Tolerance in world units (≈ 0.4% of the scene radius). pub bias: f32, } impl EyeDepth { - /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at 4096). + /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]). pub fn render(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth { - let (w, h) = (width.clamp(1, 4096), height.clamp(1, 4096)); - let aspect = w as f32 / h as f32; - let vp = camera.view_proj(aspect); + let (width, height) = (width.clamp(1, MAX_SIZE), height.clamp(1, MAX_SIZE)); + let view_proj = camera.view_proj(width as f32 / height as f32); let eye = camera.eye(); - // Project every vertex once. - let clip: Vec = mesh.positions.iter().map(|p| vp * p.extend(1.0)).collect(); - let screen: Vec> = - clip.iter().map(|c| (c.w > 1e-5).then(|| ((c.x / c.w * 0.5 + 0.5) * w as f32, (0.5 - c.y / c.w * 0.5) * h as f32))).collect(); - let dist_v: Vec = mesh.positions.iter().map(|p| p.distance(eye)).collect(); - let bands = (h as usize).div_ceil(BAND); - let mut bins: Vec> = vec![Vec::new(); bands]; - for t in 0..mesh.triangle_count() { - let Some([a, b, c]) = mesh.tri(t) else { continue }; - let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue }; - let y0 = pa.1.min(pb.1).min(pc.1).floor().max(0.0); - let y1 = pa.1.max(pb.1).max(pc.1).ceil().min(h as f32); - if y1 <= y0 || !y0.is_finite() || !y1.is_finite() { + + // Project every vertex once + let screen: Vec> = mesh + .positions + .iter() + .map(|position| { + let clip: Vec4 = view_proj * position.extend(1.0); + (clip.w > MIN_CLIP_W).then(|| ((clip.x / clip.w * 0.5 + 0.5) * width as f32, (0.5 - clip.y / clip.w * 0.5) * height as f32)) + }) + .collect(); + let vertex_distance: Vec = mesh.positions.iter().map(|position| position.distance(eye)).collect(); + + // Bin each triangle into the bands of rows it covers + let mut bands: Vec> = vec![Vec::new(); (height as usize).div_ceil(BAND)]; + for triangle in 0..mesh.triangle_count() { + let Some([first, second, third]) = mesh.tri(triangle) else { continue }; + let (Some(Some(first)), Some(Some(second)), Some(Some(third))) = (screen.get(first), screen.get(second), screen.get(third)) else { continue }; + + let top = first.1.min(second.1).min(third.1).floor().max(0.0); + let bottom = first.1.max(second.1).max(third.1).ceil().min(height as f32); + if bottom <= top || !top.is_finite() || !bottom.is_finite() { continue; } - let (b0, b1) = (y0 as usize / BAND, ((y1 as usize).saturating_sub(1)) / BAND); - for bin in bins.iter_mut().take(b1 + 1).skip(b0) { - bin.push(t as u32); + let (first_band, last_band) = (top as usize / BAND, (bottom as usize).saturating_sub(1) / BAND); + for band in bands.iter_mut().take(last_band + 1).skip(first_band) { + band.push(triangle as u32); } } - let mut dist = vec![f32::MAX; (w * h) as usize]; - dist.par_chunks_mut(BAND * w as usize).enumerate().for_each(|(bi, rows)| { - let row0 = bi * BAND; - let nrows = rows.len() / w as usize; - for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) { - let Some([a, b, c]) = mesh.tri(t as usize) else { continue }; - let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue }; - let (da, db, dc) = (dist_v[a], dist_v[b], dist_v[c]); - let area = (pb.0 - pa.0) * (pc.1 - pa.1) - (pb.1 - pa.1) * (pc.0 - pa.0); - if area.abs() < 1e-9 { + + let mut dist = vec![f32::MAX; (width * height) as usize]; + let mut triangle = vec![NO_TRI; (width * height) as usize]; + let band_len = BAND * width as usize; + dist.par_chunks_mut(band_len).zip(triangle.par_chunks_mut(band_len)).enumerate().for_each(|(band, (band_dist, band_triangles))| { + let first_row = band * BAND; + let row_count = band_dist.len() / width as usize; + for &candidate in bands.get(band).map(Vec::as_slice).unwrap_or(&[]) { + let Some(corners) = mesh.tri(candidate as usize) else { continue }; + let [first, second, third] = corners; + let (Some(Some(first_point)), Some(Some(second_point)), Some(Some(third_point))) = (screen.get(first), screen.get(second), screen.get(third)) + else { + continue; + }; + let corner_distance = corners.map(|vertex| vertex_distance[vertex]); + let area = + (second_point.0 - first_point.0) * (third_point.1 - first_point.1) - (second_point.1 - first_point.1) * (third_point.0 - first_point.0); + if area.abs() < MIN_SCREEN_AREA { continue; } - let x0 = pa.0.min(pb.0).min(pc.0).floor().max(0.0) as usize; - let x1 = (pa.0.max(pb.0).max(pc.0).ceil().min(w as f32)) as usize; - let y0 = (pa.1.min(pb.1).min(pc.1).floor().max(row0 as f32)) as usize; - let y1 = (pa.1.max(pb.1).max(pc.1).ceil().min((row0 + nrows) as f32)) as usize; - for y in y0.max(row0)..y1 { - for x in x0..x1.min(w as usize) { - let (px, py) = (x as f32 + 0.5, y as f32 + 0.5); - let w0 = ((pb.0 - px) * (pc.1 - py) - (pb.1 - py) * (pc.0 - px)) / area; - let w1 = ((pc.0 - px) * (pa.1 - py) - (pc.1 - py) * (pa.0 - px)) / area; - let w2 = 1.0 - w0 - w1; - if w0 < -1e-4 || w1 < -1e-4 || w2 < -1e-4 { + + let left = first_point.0.min(second_point.0).min(third_point.0).floor().max(0.0) as usize; + let right = (first_point.0.max(second_point.0).max(third_point.0).ceil().min(width as f32)) as usize; + let top = (first_point.1.min(second_point.1).min(third_point.1).floor().max(first_row as f32)) as usize; + let bottom = (first_point.1.max(second_point.1).max(third_point.1).ceil().min((first_row + row_count) as f32)) as usize; + for row in top.max(first_row)..bottom { + for column in left..right.min(width as usize) { + let (sample_x, sample_y) = (column as f32 + 0.5, row as f32 + 0.5); + let first_weight = + ((second_point.0 - sample_x) * (third_point.1 - sample_y) - (second_point.1 - sample_y) * (third_point.0 - sample_x)) / area; + let second_weight = + ((third_point.0 - sample_x) * (first_point.1 - sample_y) - (third_point.1 - sample_y) * (first_point.0 - sample_x)) / area; + let third_weight = 1.0 - first_weight - second_weight; + if first_weight < -EDGE_TOLERANCE || second_weight < -EDGE_TOLERANCE || third_weight < -EDGE_TOLERANCE { continue; } - let d = w0 * da + w1 * db + w2 * dc; - if let Some(slot) = rows.get_mut((y - row0) * w as usize + x) - && d < *slot + + let distance = first_weight * corner_distance[0] + second_weight * corner_distance[1] + third_weight * corner_distance[2]; + let at = (row - first_row) * width as usize + column; + if let Some(slot) = band_dist.get_mut(at) + && distance < *slot { - *slot = d; + *slot = distance; + if let Some(nearest) = band_triangles.get_mut(at) { + *nearest = candidate; + } } } } } }); - EyeDepth { width: w, height: h, view_proj: vp, eye, dist, bias: mesh.radius() * 0.004 } + + EyeDepth { width, height, view_proj, eye, dist, triangle, bias: mesh.radius() * BIAS_PER_RADIUS } } /// Whether world point `p` is visible (not hidden behind other geometry, inside the view). diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 87e9d84b..c42ee799 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -912,12 +912,14 @@ fn mesh_map_color(map: BakedMap) -> Color32 { /// The Properties tab title: what the panel edits. pub(crate) fn properties_title(app: &TextureCraftApp) -> String { - let p = &app.session.doc.project; - let what = match (app.session.selected_layer().and_then(|id| p.layers.get(&id)), app.session.target) { - (Some(_), StackTarget::Effect(e)) => p.effect(e).map(|(_, x)| x.name.clone()).unwrap_or_default(), - (Some(l), StackTarget::Content) if matches!(l.kind, LayerKind::Fill(_)) => tr("Fill").to_string(), - (Some(l), StackTarget::Content) if l.is_group() => tr("Folder").to_string(), - (Some(l), StackTarget::Content) if l.instance_source().is_some() => tr("Instance").to_string(), + let project = &app.session.doc.project; + let what = match (app.session.selected_layer().and_then(|id| project.layers.get(&id)), app.session.target) { + // Polygon fill keeps its own properties whatever is selected + _ if app.session.tool.tool == Tool::PolygonFill => tr(app.session.tool.tool.label()).to_string(), + (Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| found.name.clone()).unwrap_or_default(), + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => tr("Fill").to_string(), + (Some(layer), StackTarget::Content) if layer.is_group() => tr("Folder").to_string(), + (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => tr("Instance").to_string(), _ => tr(app.session.tool.tool.label()).to_string(), }; format!("{} - {what}", tr("Properties")) @@ -927,12 +929,14 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); } -/// What the Properties panel edits: the selected effect, fill, folder or instance, else the tool +/// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder or instance, else the tool pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); match (&selected, app.session.target) { + // Polygon fill shows its own settings and says what it fills into, whatever is selected + _ if app.session.tool.tool == Tool::PolygonFill => polygon_fill_properties(app, ui), (Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect), (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), (Some(layer), StackTarget::Content) if layer.is_group() => { @@ -1144,6 +1148,104 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(RichText::new(hint).size(10.5).color(tk.text_dim)); } +/// Width of the label column in polygon fill's properties +const POLYGON_FILL_LABEL_WIDTH: f32 = 108.0; + +/// Polygon fill's properties: how it selects and fills, its blending, then what it fills with (material, mask gray, or why it can't fill) +fn polygon_fill_properties(app: &mut TextureCraftApp, ui: &mut Ui) { + use texturecraft_engine::FillHitTest; + + let button_size = ui.spacing().interact_size.y; + ui.label(caption(&tr("Polygon fill").to_uppercase())); + property_row(ui, tr("Selection mode"), tr("A click fills what is under it; a dragged rectangle fills what it selects as it grows"), |ui| { + icon_button(ui, ic::SELECTION, tr("Rectangle fill"), true, button_size); + }); + property_row( + ui, + tr("Fill mode"), + tr("Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands"), + |ui| crate::toolbar::fill_mode_buttons(app, ui), + ); + property_row(ui, tr("Hit-test"), tr("How a rectangle selects polygons"), |ui| { + for (hit_test, icon, tooltip) in [ + (FillHitTest::Intersection, ic::INTERSECT_SQUARE, tr("Intersection: fill polygons the rectangle touches")), + (FillHitTest::ContainedCenter, ic::SELECTION_FOREGROUND, tr("Contained center: fill polygons whose center is in the rectangle")), + ] { + if icon_button(ui, icon, tooltip, app.session.tool.fill_hit_test == hit_test, button_size).clicked() { + app.session.tool.fill_hit_test = hit_test; + } + } + }); + ui.horizontal(|ui| { + ui.checkbox(&mut app.session.tool.fill_visible_only, tr("Visible polygons only")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, tr("Fill only polygons the camera sees (3D view)"))); + }); + section(ui, "sec_polygon_fill_blending", tr("Blending"), false, |ui| { + let mut opacity = app.session.tool.brush.opacity * 100.0; + if slider(ui, tr("Opacity"), &mut opacity, 0.0..=100.0, 0).changed() { + app.session.tool.brush.opacity = (opacity / 100.0).clamp(0.0, 1.0); + } + }); + ui.separator(); + + match polygon_fill_paints_mask(app) { + Ok(false) => { + ui.label(caption(&tr("Material").to_uppercase())); + material_controls(app, ui); + } + Ok(true) => { + ui.label(caption(&tr("Grayscale").to_uppercase())); + let mut gray = app.session.tool.mask_value; + if slider(ui, tr("Value"), &mut gray, 0.0..=1.0, 2).changed() { + app.session.tool.mask_value = gray; + } + } + Err(note) => { + ui.label(RichText::new(note).color(Tokens::get(ui.ctx()).text_dim)); + } + } +} + +/// One polygon fill setting: its label in a fixed column, its `controls`, and an info icon with `info` at the right edge +fn property_row(ui: &mut Ui, label: &str, info: &str, controls: impl FnOnce(&mut Ui)) { + ui.horizontal(|ui| { + let label_width = ui.label(label).rect.width(); + ui.add_space((POLYGON_FILL_LABEL_WIDTH - label_width - ui.spacing().item_spacing.x).max(0.0)); + controls(ui); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, info)); + }); +} + +/// A dim info icon explaining a setting on hover +fn info_icon(ui: &mut Ui, text: &str) { + ui.label(RichText::new(ic::INFO).color(Tokens::get(ui.ctx()).text_dim)).on_hover_text(text); +} + +/// What a polygon fill paints into now: Ok(true) a mask (gray), Ok(false) layer content (material), or a note on why it can't fill +fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result { + if app.session.quick_mask.editing { + return Err(tr("Editing the quick mask: fills paint where painting is allowed. Press U to finish.").to_string()); + } + + let project = &app.session.doc.project; + let Some(layer) = app.session.selected_layer().and_then(|id| project.layers.get(&id)) else { + return Err(tr("Select a paint layer or a layer's mask to fill").to_string()); + }; + + match app.session.target { + StackTarget::Mask => Ok(true), + StackTarget::Effect(_) => Ok(!targets_content(app)), + StackTarget::Content => { + let content = project.content_layer(layer.id).unwrap_or(layer); + if matches!(content.kind, LayerKind::Paint) { + Ok(false) + } else { + Err(trf("\"{layer}\" can't be filled: select a paint layer or a layer's mask", &[("layer", &layer.name)])) + } + } + } +} + fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { let b = &mut app.session.tool.brush; ui.label(caption(tr("Brush"))); @@ -1365,59 +1467,68 @@ fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) { /// Tooltip of the material channel chips. pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only"; +/// The tool's material under a "Material" heading fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Material"))); - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + material_controls(app, ui); +} + +/// The tool's material: channel chips, then each enabled channel's value (or the mask gray while painting a mask) +fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { + use texturecraft_engine::core::ChannelKind; + + let tokens = Tokens::get(ui.ctx()); + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); ui.horizontal_wrapped(|ui| { - for c in &chans { - let on = app.session.tool.enabled.contains(c); - if chip(ui, tr(c.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() { - let solo = ui.input(|i| i.modifiers.alt); - app.run("tool.material", json!({"channel": c.id(), "enabled": solo || !on, "solo": solo})); + for channel in &channels { + let on = app.session.tool.enabled.contains(channel); + if chip(ui, tr(channel.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() { + let solo = ui.input(|input| input.modifiers.alt); + app.run("tool.material", json!({"channel": channel.id(), "enabled": solo || !on, "solo": solo})); } } }); ui.add_space(4.0); - let mask_mode = !targets_content(app); - if mask_mode { - let mut v = app.session.tool.mask_value; - if slider(ui, tr("Mask value (gray)"), &mut v, 0.0..=1.0, 2).changed() { - app.session.tool.mask_value = v; + + if !targets_content(app) { + let mut gray = app.session.tool.mask_value; + if slider(ui, tr("Mask value (gray)"), &mut gray, 0.0..=1.0, 2).changed() { + app.session.tool.mask_value = gray; } return; } - for c in chans { - if !app.session.tool.enabled.contains(&c) { + + for channel in channels { + if !app.session.tool.enabled.contains(&channel) { continue; } - let mut v = app.session.tool.values.get(&c).copied().unwrap_or(c.default_value()); - match c.kind() { - texturecraft_engine::core::ChannelKind::Color => { + let mut value = app.session.tool.values.get(&channel).copied().unwrap_or(channel.default_value()); + match channel.kind() { + ChannelKind::Color => { ui.horizontal(|ui| { - ui.label(tr(c.label())); - if color_swatch(ui, &format!("tool_{}", c.id()), &mut v, ui.available_width() - 4.0) { - app.session.tool.values.insert(c, v); + ui.label(tr(channel.label())); + if color_swatch(ui, &format!("tool_{}", channel.id()), &mut value, ui.available_width() - 4.0) { + app.session.tool.values.insert(channel, value); } }); } - texturecraft_engine::core::ChannelKind::NormalMap => { - ui.label(RichText::new(tr("Normal: painting uses the flat normal")).color(tk.text_dim)); + ChannelKind::NormalMap => { + ui.label(RichText::new(tr("Normal: painting uses the flat normal")).color(tokens.text_dim)); } - texturecraft_engine::core::ChannelKind::Signed => { - if slider(ui, tr(c.label()), &mut v[0], -1.0..=1.0, 2).changed() { - app.session.tool.values.insert(c, [v[0]; 3]); + ChannelKind::Signed => { + if slider(ui, tr(channel.label()), &mut value[0], -1.0..=1.0, 2).changed() { + app.session.tool.values.insert(channel, [value[0]; 3]); } } - texturecraft_engine::core::ChannelKind::Scalar => { - if slider(ui, tr(c.label()), &mut v[0], 0.0..=1.0, 2).changed() { - app.session.tool.values.insert(c, [v[0]; 3]); + ChannelKind::Scalar => { + if slider(ui, tr(channel.label()), &mut value[0], 0.0..=1.0, 2).changed() { + app.session.tool.values.insert(channel, [value[0]; 3]); } } } } if app.session.tool.tool == Tool::Eraser { - ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tk.text_dim)); + ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tokens.text_dim)); } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 0f2e023f..4c50e9ac 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1035,4 +1035,24 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "النقرة تملأ ما تحتها، والمستطيل المسحوب يملأ ما يحدده أثناء اتساعه", + ), + ("Contained center: fill polygons whose center is in the rectangle", "المركز المحتوى: تعبئة المضلعات التي يقع مركزها داخل المستطيل"), + ("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "تحرير القناع السريع: ترسم التعبئات حيث يُسمح بالرسم. اضغط U للإنهاء."), + ("Fill mode", "وضع التعبئة"), + ("Fill only polygons the camera sees (3D view)", "تعبئة المضلعات التي تراها الكاميرا فقط (العرض ثلاثي الأبعاد)"), + ("Hit-test", "اختبار الإصابة"), + ("How a rectangle selects polygons", "كيف يحدد المستطيل المضلعات"), + ("Intersection: fill polygons the rectangle touches", "التقاطع: تعبئة المضلعات التي يلمسها المستطيل"), + ("Rectangle fill", "تعبئة مستطيلة"), + ("Select a paint layer or a layer's mask to fill", "حدد طبقة رسم أو قناع طبقة للتعبئة"), + ("Selection mode", "وضع التحديد"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "المثلث يملأ مثلثات منفردة، والمضلع رباعيات ومضلعات كاملة، والمجسم الهندسة المتصلة، وجزيرة UV جزر UV", + ), + ("Visible polygons only", "المضلعات المرئية فقط"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" لا يمكن تعبئتها: حدد طبقة رسم أو قناع طبقة"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 77cf296b..63ec501e 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1078,4 +1078,27 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Auflösungsüberschreibung entfernen"), ("Texture set resolution", "Auflösung des Textursets"), ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Ein Klick füllt, was darunter liegt; ein aufgezogenes Rechteck füllt, was es beim Aufziehen erfasst", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Enthaltener Mittelpunkt: Polygone füllen, deren Mittelpunkt im Rechteck liegt"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Schnellmaske wird bearbeitet: Füllungen markieren, wo Malen erlaubt ist. Zum Beenden U drücken.", + ), + ("Fill mode", "Füllmodus"), + ("Fill only polygons the camera sees (3D view)", "Nur Polygone füllen, die die Kamera sieht (3D-Ansicht)"), + ("Hit-test", "Treffertest"), + ("How a rectangle selects polygons", "Wie ein Rechteck Polygone auswählt"), + ("Intersection: fill polygons the rectangle touches", "Schnittmenge: Polygone füllen, die das Rechteck berührt"), + ("Rectangle fill", "Rechteckfüllung"), + ("Select a paint layer or a layer's mask to fill", "Wähle zum Füllen eine Malebene oder eine Ebenenmaske"), + ("Selection mode", "Auswahlmodus"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Dreieck füllt einzelne Dreiecke, Polygon ganze Vierecke und N-Ecke, Mesh die zusammenhängende Geometrie, UV-Insel die UV-Inseln", + ), + ("Visible polygons only", "Nur sichtbare Polygone"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" kann nicht gefüllt werden: Wähle eine Malebene oder eine Ebenenmaske"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 4153783e..99fd2177 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1063,4 +1063,30 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Quitar resolución personalizada"), ("Texture set resolution", "Resolución del conjunto de texturas"), ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic rellena lo que hay debajo; un rectángulo arrastrado rellena lo que selecciona mientras crece", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contenido: rellenar los polígonos cuyo centro está en el rectángulo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Editando la máscara rápida: los rellenos pintan donde se permite pintar. Pulsa U para terminar.", + ), + ("Fill mode", "Modo de relleno"), + ("Fill only polygons the camera sees (3D view)", "Rellenar solo los polígonos que ve la cámara (vista 3D)"), + ("Hit-test", "Prueba de selección"), + ("How a rectangle selects polygons", "Cómo selecciona polígonos un rectángulo"), + ("Intersection: fill polygons the rectangle touches", "Intersección: rellenar los polígonos que toca el rectángulo"), + ("Rectangle fill", "Relleno rectangular"), + ("Select a paint layer or a layer's mask to fill", "Selecciona una capa de pintura o una máscara de capa para rellenar"), + ("Selection mode", "Modo de selección"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triángulo rellena triángulos sueltos, Polígono cuadriláteros y n-gonos enteros, Malla la geometría conectada, Isla UV las islas UV", + ), + ("Visible polygons only", "Solo polígonos visibles"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" no se puede rellenar: selecciona una capa de pintura o una máscara de capa", + ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 0c07e5a4..4ef684a1 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1087,4 +1087,30 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Supprimer la résolution personnalisée"), ("Texture set resolution", "Résolution de l'ensemble de textures"), ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic remplit ce qui est dessous ; un rectangle tracé remplit ce qu'il sélectionne à mesure qu'il grandit", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centre contenu : remplir les polygones dont le centre est dans le rectangle"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Modification du masque rapide : les remplissages peignent là où la peinture est autorisée. Appuyez sur U pour terminer.", + ), + ("Fill mode", "Mode de remplissage"), + ("Fill only polygons the camera sees (3D view)", "Remplir uniquement les polygones que voit la caméra (vue 3D)"), + ("Hit-test", "Test de sélection"), + ("How a rectangle selects polygons", "Comment un rectangle sélectionne les polygones"), + ("Intersection: fill polygons the rectangle touches", "Intersection : remplir les polygones que touche le rectangle"), + ("Rectangle fill", "Remplissage rectangulaire"), + ("Select a paint layer or a layer's mask to fill", "Sélectionnez un calque de peinture ou un masque de calque à remplir"), + ("Selection mode", "Mode de sélection"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triangle remplit des triangles seuls, Polygone des quads et n-gones entiers, Maillage la géométrie connectée, Îlot UV les îlots UV", + ), + ("Visible polygons only", "Polygones visibles uniquement"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "« {layer} » ne peut pas être rempli : sélectionnez un calque de peinture ou un masque de calque", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index b4bd33b3..44171f06 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1072,4 +1072,30 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Rimuovi risoluzione personalizzata"), ("Texture set resolution", "Risoluzione del set di texture"), ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic riempie ciò che c'è sotto; un rettangolo trascinato riempie ciò che seleziona mentre si allarga", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contenuto: riempi i poligoni il cui centro è nel rettangolo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Modifica della maschera rapida: i riempimenti dipingono le aree in cui è consentito dipingere. Premi U per terminare.", + ), + ("Fill mode", "Modalità di riempimento"), + ("Fill only polygons the camera sees (3D view)", "Riempi solo i poligoni visti dalla camera (vista 3D)"), + ("Hit-test", "Test di selezione"), + ("How a rectangle selects polygons", "Come un rettangolo seleziona i poligoni"), + ("Intersection: fill polygons the rectangle touches", "Intersezione: riempi i poligoni toccati dal rettangolo"), + ("Rectangle fill", "Riempimento rettangolare"), + ("Select a paint layer or a layer's mask to fill", "Seleziona un livello di pittura o una maschera di livello da riempire"), + ("Selection mode", "Modalità di selezione"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triangolo riempie singoli triangoli, Poligono quad e n-goni interi, Mesh la geometria connessa, Isola UV le isole UV", + ), + ("Visible polygons only", "Solo poligoni visibili"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" non può essere riempito: seleziona un livello di pittura o una maschera di livello", + ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index f764e268..9b4b7fe9 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1057,4 +1057,30 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "クリックでその下を塗りつぶし、ドラッグした矩形は広げるにつれて選択した範囲を塗りつぶします", + ), + ("Contained center: fill polygons whose center is in the rectangle", "中心を含む: 中心が矩形内にあるポリゴンを塗りつぶします"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "クイックマスク編集中: 塗りつぶしでペイントを許可する範囲を塗ります。Uキーで終了します。", + ), + ("Fill mode", "塗りつぶしモード"), + ("Fill only polygons the camera sees (3D view)", "カメラから見えるポリゴンだけを塗りつぶします (3Dビュー)"), + ("Hit-test", "ヒットテスト"), + ("How a rectangle selects polygons", "矩形がポリゴンを選択する方法"), + ("Intersection: fill polygons the rectangle touches", "交差: 矩形が触れるポリゴンを塗りつぶします"), + ("Rectangle fill", "矩形塗りつぶし"), + ("Select a paint layer or a layer's mask to fill", "塗りつぶすペイントレイヤーまたはレイヤーマスクを選択してください"), + ("Selection mode", "選択モード"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "三角形は個々の三角形、ポリゴンは四角形やNゴン全体、メッシュはつながったジオメトリ、UVアイランドはUVアイランドを塗りつぶします", + ), + ("Visible polygons only", "表示されているポリゴンのみ"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "「{layer}」は塗りつぶせません: ペイントレイヤーまたはレイヤーマスクを選択してください", + ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index a1c8d363..e11e5ccb 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1045,4 +1045,27 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "클릭하면 아래에 있는 것을 채우고, 드래그한 사각형은 커지면서 선택한 것을 채웁니다", + ), + ("Contained center: fill polygons whose center is in the rectangle", "중심 포함: 중심이 사각형 안에 있는 폴리곤을 채웁니다"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "퀵 마스크 편집 중: 채우기로 페인팅을 허용할 영역을 칠합니다. U를 눌러 완료하세요.", + ), + ("Fill mode", "채우기 모드"), + ("Fill only polygons the camera sees (3D view)", "카메라에 보이는 폴리곤만 채웁니다 (3D 뷰)"), + ("Hit-test", "히트 테스트"), + ("How a rectangle selects polygons", "사각형이 폴리곤을 선택하는 방식"), + ("Intersection: fill polygons the rectangle touches", "교차: 사각형에 닿는 폴리곤을 채웁니다"), + ("Rectangle fill", "사각형 채우기"), + ("Select a paint layer or a layer's mask to fill", "채울 페인트 레이어나 레이어 마스크를 선택하세요"), + ("Selection mode", "선택 모드"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "삼각형은 개별 삼각형, 폴리곤은 사각형과 N각형 전체, 메시는 연결된 지오메트리, UV 아일랜드는 UV 아일랜드를 채웁니다", + ), + ("Visible polygons only", "보이는 폴리곤만"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\"은(는) 채울 수 없습니다: 페인트 레이어나 레이어 마스크를 선택하세요"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 880b62ff..307a93e6 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1060,4 +1060,30 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Remover resolução personalizada"), ("Texture set resolution", "Resolução do conjunto de texturas"), ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Um clique preenche o que está embaixo; um retângulo arrastado preenche o que seleciona enquanto cresce", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contido: preencher os polígonos cujo centro está no retângulo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Editando a máscara rápida: os preenchimentos pintam onde a pintura é permitida. Pressione U para concluir.", + ), + ("Fill mode", "Modo de preenchimento"), + ("Fill only polygons the camera sees (3D view)", "Preencher apenas os polígonos que a câmera vê (vista 3D)"), + ("Hit-test", "Teste de seleção"), + ("How a rectangle selects polygons", "Como um retângulo seleciona polígonos"), + ("Intersection: fill polygons the rectangle touches", "Interseção: preencher os polígonos que o retângulo toca"), + ("Rectangle fill", "Preenchimento retangular"), + ("Select a paint layer or a layer's mask to fill", "Selecione uma camada de pintura ou uma máscara de camada para preencher"), + ("Selection mode", "Modo de seleção"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triângulo preenche triângulos isolados, Polígono quads e n-gons inteiros, Malha a geometria conectada, Ilha UV as ilhas UV", + ), + ("Visible polygons only", "Apenas polígonos visíveis"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" não pode ser preenchida: selecione uma camada de pintura ou uma máscara de camada", + ), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index f894f1ad..d3d35296 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1003,4 +1003,21 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("A click fills what is under it; a dragged rectangle fills what it selects as it grows", "单击填充其下方的内容;拖出的矩形在扩大时填充其选中的内容"), + ("Contained center: fill polygons whose center is in the rectangle", "包含中心:填充中心位于矩形内的多边形"), + ("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "正在编辑快速遮罩:填充绘制在允许绘画的区域。按 U 完成。"), + ("Fill mode", "填充模式"), + ("Fill only polygons the camera sees (3D view)", "仅填充相机可见的多边形(3D 视图)"), + ("Hit-test", "命中测试"), + ("How a rectangle selects polygons", "矩形选择多边形的方式"), + ("Intersection: fill polygons the rectangle touches", "相交:填充矩形触及的多边形"), + ("Rectangle fill", "矩形填充"), + ("Select a paint layer or a layer's mask to fill", "选择要填充的绘画图层或图层遮罩"), + ("Selection mode", "选择模式"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "三角形填充单个三角形,多边形填充整个四边形和 n 边形,网格填充相连的几何体,UV 岛填充 UV 岛", + ), + ("Visible polygons only", "仅可见多边形"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "“{layer}”无法填充:请选择绘画图层或图层遮罩"), ]; diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index eee357f7..889d2de7 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -281,19 +281,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) path_controls(app, ui); } } - Tool::PolygonFill => { - use texturecraft_engine::FillMode; - - for (fill_mode, icon, tooltip) in [ - (FillMode::Triangle, ic::POLYGON, tr("Triangle fill")), - (FillMode::UvIsland, ic::SHAPES, tr("UV island fill")), - (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), - ] { - if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, button_size).clicked() { - app.session.tool.fill_mode = fill_mode; - } - } - } + Tool::PolygonFill => fill_mode_buttons(app, ui), Tool::ColorPicker => { ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tokens.text_dim)); } @@ -317,6 +305,23 @@ fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } } +/// Polygon fill's fill modes (top bar and properties) +pub fn fill_mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + use texturecraft_engine::FillMode; + + let button_size = ui.spacing().interact_size.y; + for (fill_mode, icon, tooltip) in [ + (FillMode::Triangle, ic::TRIANGLE, tr("Triangle fill")), + (FillMode::Polygon, ic::PARALLELOGRAM, tr("Polygon fill")), + (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), + (FillMode::UvIsland, ic::CHECKERBOARD, tr("UV island fill")), + ] { + if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, button_size).clicked() { + app.session.tool.fill_mode = fill_mode; + } + } +} + /// Path tool options and actions (top bar and properties) pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let button_size = ui.spacing().interact_size.y; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..91f816e9 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -9,7 +9,7 @@ use serde_json::json; use texturecraft_engine::camera_cmds::DEFAULT_CAMERA; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::glam::{Vec2, Vec3}; -use texturecraft_engine::{Tool, ViewMode}; +use texturecraft_engine::{Session, Tool, ViewMode}; use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind}; use crate::TextureCraftApp; @@ -213,12 +213,14 @@ fn shade(app: &TextureCraftApp) -> Shade { }; let set_index = app.session.ts(); let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); + // Polygon fill shows the polygons it fills without changing the saved wireframe toggles + let polygon_fill = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, view_mode, channel, - wireframe: app.ui.uv_wireframe, - wireframe_3d: app.ui.wireframe_3d, + wireframe: app.ui.uv_wireframe || polygon_fill, + wireframe_3d: app.ui.wireframe_3d || polygon_fill, ..Shade::from_project(&app.session.doc.project) } } @@ -575,8 +577,17 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let path_tool = app.session.tool.tool == Tool::Path; let viewport = app.session.viewport; let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point); + let mut fill_box = None; if painting && path_tool { path_input(app, ui, &response, false, |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show); + } else if painting && app.session.tool.tool == Tool::PolygonFill { + fill_box = polygon_fill_input( + app, + ui, + &response, + |session, point| session.polygon_fill(local(point), viewport), + |session, corner, opposite| session.drag_polygon_fill_box(local(corner), local(opposite), viewport), + ); } else if painting { let pressure = pen_pressure(ui); if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { @@ -621,6 +632,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); + polygon_fill_box_overlay(ui, rect, fill_box); // Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); @@ -1003,6 +1015,52 @@ fn rubber_band(ui: &Ui, rect: Rect, from: Pos2, to: Pos2) { p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(1.0, Color32::from_white_alpha(200)), 6.0, 4.0)); } +/// Polygon fill in a view: a click fills one target, a drag fills its box live (one undo step); returns the box to draw over the view image +fn polygon_fill_input( + app: &mut TextureCraftApp, + ui: &Ui, + response: &egui::Response, + fill_at: impl Fn(&mut Session, Pos2) -> texturecraft_engine::Result, + drag_box: impl Fn(&mut Session, Pos2, Pos2) -> texturecraft_engine::Result, +) -> Option { + let origin_id = response.id.with("polygon_fill_box"); + let dragging = response.dragged_by(PointerButton::Primary); + let released = response.drag_stopped_by(PointerButton::Primary); + let held = ui.input(|input| input.pointer.primary_down()); + if !held && !released { + // A drag this view started and cut short (Alt, a second finger) keeps what it filled as one step + if ui.data_mut(|data| data.remove_temp::(origin_id)).is_some() { + app.session.end_polygon_fill_box(); + } + } else if dragging && let Some(press) = ui.input(|input| input.pointer.press_origin()) { + ui.data_mut(|data| data.insert_temp(origin_id, press)); + } + + let origin = ui.data(|data| data.get_temp::(origin_id)); + let pointer = ui.input(|input| input.pointer.latest_pos()); + let (filled, dragged_box) = match (origin, pointer) { + _ if response.clicked_by(PointerButton::Primary) => (response.interact_pointer_pos().map(|point| fill_at(&mut app.session, point)), None), + (Some(origin), Some(pointer)) if released => (Some(drag_box(&mut app.session, origin, pointer).map(|_| app.session.end_polygon_fill_box())), None), + (Some(origin), Some(pointer)) => (Some(drag_box(&mut app.session, origin, pointer)), Some(Rect::from_two_pos(origin, pointer))), + _ => (None, None), + }; + if let Some(Err(error)) = filled { + app.toast(error.to_string(), true); + } + dragged_box +} + +/// How strongly the polygon fill box tints what it covers (0..1) +const FILL_BOX_TINT: f32 = 0.15; + +/// The polygon fill box being dragged, over view `rect` +fn polygon_fill_box_overlay(ui: &Ui, rect: Rect, fill_box: Option) { + let Some(fill_box) = fill_box else { return }; + + let accent = Tokens::get(ui.ctx()).viewport_accent; + ui.painter_at(rect).rect(fill_box, 0.0, accent.gamma_multiply(FILL_BOX_TINT), Stroke::new(1.0, accent), egui::StrokeKind::Inside); +} + /// V held with the Clone tool in painting mode: clicks set the clone source. fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool { app.ui.mode == crate::state::Mode::Painting @@ -1213,8 +1271,17 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Painting in UV space let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held; + let mut fill_box = None; if painting && path_tool { path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); + } else if painting && app.session.tool.tool == Tool::PolygonFill { + fill_box = polygon_fill_input( + app, + ui, + &response, + |session, point| session.polygon_fill_uv(to_uv(point)), + |session, corner, opposite| session.drag_polygon_fill_box_uv(to_uv(corner), to_uv(opposite)), + ); } else if painting { let pressure = pen_pressure(ui); if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { @@ -1254,6 +1321,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); + polygon_fill_box_overlay(ui, rect, fill_box); crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View2d); // The UV tile outlines (numbered for UDIM sets) and the path being edited diff --git a/crates/ui-egui/tests/polygon_fill.rs b/crates/ui-egui/tests/polygon_fill.rs new file mode 100644 index 00000000..dc007035 --- /dev/null +++ b/crates/ui-egui/tests/polygon_fill.rs @@ -0,0 +1,85 @@ +//! Polygon fill in the views: a click fills one target and a box drag fills what the box selects, each as one undo step + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2}; +use egui_kittest::Harness; +use texturecraft_engine::Tool; +use texturecraft_engine::core::Channel; +use texturecraft_ui_egui::TextureCraftApp; + +/// The sample project in the default split layout at 1600 x 960 with the polygon fill tool +fn polygon_fill_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + harness.run_steps(4); + harness +} + +/// Drag the primary button from `from` to `to` in a few moves +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + for step in 1..=4 { + harness.hover_at(from + (to - from) * (step as f32 / 4.0)); + harness.run_steps(1); + } + + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// Press and release the primary button at `at` +fn click(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) { + harness.hover_at(at); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// Allocated tiles in the selected layer's base color +fn painted_tiles(harness: &Harness<'_, TextureCraftApp>) -> usize { + let session = &harness.state().session; + let layer = session.selected_layer().expect("a selected layer"); + session.doc.pixels.layer(layer, Channel::BaseColor).map_or(0, |image| image.allocated_count()) +} + +/// The undo steps recorded so far +fn history(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.history_labels() +} + +#[test] +fn a_box_drag_in_the_3d_view_is_one_fill_over_more_than_a_click() { + let mut clicked = polygon_fill_app(); + let center = clicked.state().viewport_rect.center(); + let before = history(&clicked).len(); + click(&mut clicked, center); + assert_eq!(history(&clicked).len(), before + 1, "a click fills one triangle"); + + let mut boxed = polygon_fill_app(); + drag(&mut boxed, center - vec2(120.0, 120.0), center + vec2(120.0, 120.0)); + assert_eq!(history(&boxed).len(), before + 1); + assert_eq!(history(&boxed).last().map(String::as_str), Some("Polygon fill")); + assert!( + painted_tiles(&boxed) > painted_tiles(&clicked), + "the box fills every triangle in it: {} tiles vs {}", + painted_tiles(&boxed), + painted_tiles(&clicked) + ); +} + +#[test] +fn a_box_drag_in_the_2d_view_is_one_fill() { + let mut harness = polygon_fill_app(); + let view_3d = harness.state().viewport_rect; + let center = pos2(view_3d.right() + view_3d.width() * 0.5, view_3d.center().y); + let before = history(&harness).len(); + + drag(&mut harness, center - vec2(80.0, 20.0), center + vec2(80.0, 20.0)); + assert_eq!(history(&harness).len(), before + 1); + assert_eq!(history(&harness).last().map(String::as_str), Some("Polygon fill")); +} From 538220069de65d4f75dd905c72664a5707f779ef Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 07:00:18 +0000 Subject: [PATCH 32/73] Name the fill slider ranges and the test's sizes and frame counts The tri-planar hardness range is the one layer.fill.projection clamps to; scale and rotation get named slider ranges as well. --- crates/ui-egui/src/dock.rs | 15 ++++++++--- .../ui-egui/tests/fill_projection_section.rs | 25 ++++++++++++++----- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 702104c0..22474fd6 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1603,6 +1603,15 @@ fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value } } +/// Slider range of a fill's scale or tiling +const FILL_SCALE_RANGE: std::ops::RangeInclusive = 0.01..=20.0; + +/// Slider range of a UV fill's rotation, a full turn +const FILL_ROTATION_DEGREES_RANGE: std::ops::RangeInclusive = 0.0..=360.0; + +/// Tri-planar hardness: the exponent on the normal that weights the three projections, clamped to the same range by `layer.fill.projection` +const TRIPLANAR_HARDNESS_RANGE: std::ops::RangeInclusive = 1.0..=64.0; + /// A fill's projection kind, axis and tri-planar hardness, then its collapsible UV transformations; each edit sends only its field fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value) { let projection_label = fill.projection.label(); @@ -1630,7 +1639,7 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: } if let Projection::Triplanar { sharpness, .. } = &fill.projection { let mut sharpness = *sharpness; - if let Some(merge) = slider_edit(ui, tr("Hardness"), &mut sharpness, 1.0..=64.0, 1) { + if let Some(merge) = slider_edit(ui, tr("Hardness"), &mut sharpness, TRIPLANAR_HARDNESS_RANGE, 1) { edit(json!({"sharpness": sharpness, "merge": merge})); } } @@ -1650,14 +1659,14 @@ fn projection_transform(ui: &mut Ui, projection: &Projection, edit: &mut impl Fn } Projection::Decal(_) => return, }; - if let Some(merge) = slider_edit(ui, tr("Scale / tiling"), &mut scale, 0.01..=20.0, 2) { + if let Some(merge) = slider_edit(ui, tr("Scale / tiling"), &mut scale, FILL_SCALE_RANGE, 2) { edit(json!({"scale": scale, "merge": merge})); } match projection { Projection::Uv { rotation, offset, .. } => { let mut rotation_degrees = *rotation; - if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut rotation_degrees, 0.0..=360.0, 0) { + if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut rotation_degrees, FILL_ROTATION_DEGREES_RANGE, 0) { edit(json!({"rotation": rotation_degrees, "merge": merge})); } if let Some((offset, merge)) = offset_sliders(ui, ["U", "V"], *offset) { diff --git a/crates/ui-egui/tests/fill_projection_section.rs b/crates/ui-egui/tests/fill_projection_section.rs index c46b4c7e..3d6e2c20 100644 --- a/crates/ui-egui/tests/fill_projection_section.rs +++ b/crates/ui-egui/tests/fill_projection_section.rs @@ -5,23 +5,36 @@ use egui_kittest::kittest::Queryable; use serde_json::json; use texturecraft_ui_egui::TextureCraftApp; +/// Tall enough that Properties shows the whole fill without scrolling +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1400.0); + +/// Small texture and bake sizes keep the sample session fast; the panel doesn't depend on them +const TEXTURE_RESOLUTION: u32 = 256; +const BAKE_RESOLUTION: u32 = 64; + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +/// Frames for a click or selection change to reach the panel +const SETTLE_FRAMES: usize = 3; + /// The app with a new fill layer (projected as `projection`) selected in Properties, and its layer id fn app_with_fill(projection: &str) -> (Harness<'static, TextureCraftApp>, u64) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); let added = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); let layer = added["layer"].as_u64().unwrap(); texturecraft_engine::execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": projection})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); // The labels below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); - harness.run_steps(4); + harness.run_steps(STARTUP_FRAMES); (harness, layer) } fn toggle_section(harness: &mut Harness<'_, TextureCraftApp>) { harness.get_by_label("UV transformations").click(); - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); } #[test] @@ -59,10 +72,10 @@ fn each_fill_keeps_its_own_open_state() { let added = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.fill", &json!({})).unwrap(); let second = added["layer"].as_u64().unwrap(); texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": second})).unwrap(); - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); assert!(harness.query_by_label("Rotation").is_some(), "a new fill starts open"); texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": first})).unwrap(); - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); assert!(harness.query_by_label("Rotation").is_none(), "the first fill stays closed"); } From 042627589557d4b18e367bca453dc1c01df0876b Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 07:13:04 +0000 Subject: [PATCH 33/73] Tidy the fill editors and test the fill effect and cylindrical paths Name the fill's two gaps, give the edited offsets and hardness their own names, reuse the fill's id salt for the section, shorten the doc comments, and cover a fill effect's own open state and the cylindrical Axis. --- crates/ui-egui/src/dock.rs | 41 +++++++++++-------- .../ui-egui/tests/fill_projection_section.rs | 21 ++++++++++ 2 files changed, 45 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 22474fd6..db87585e 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1572,16 +1572,22 @@ fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> Str trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]) } -/// Projection and channel sources of a fill layer (`base` = {"layer"}) or fill effect (`base` = {"effect"}) filling `on`, owned by `reader` +/// Space above a fill's Material caption, setting it apart from the projection +const FILL_MATERIAL_GAP: f32 = 6.0; + +/// Space between a fill's channel chips and its channel sources +const FILL_CHANNELS_GAP: f32 = 4.0; + +/// Projection and sources of a fill layer or fill effect (`base`) for its channels `on`; `reader` owns it fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, on: &[Channel], reader: LayerId) { let salt = base.to_string(); if let Projection::Decal(decal) = &fill.projection { decal_editor(app, ui, decal, reader); } else { - projection_editor(app, ui, fill, base); + projection_editor(app, ui, fill, base, &salt); } - ui.add_space(6.0); + ui.add_space(FILL_MATERIAL_GAP); ui.label(caption(tr("Material"))); let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); ui.horizontal_wrapped(|ui| { @@ -1594,7 +1600,7 @@ fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value } }); - ui.add_space(4.0); + ui.add_space(FILL_CHANNELS_GAP); let anchors = anchors_below(app, reader); for channel in channels { if on.contains(&channel) { @@ -1609,11 +1615,11 @@ const FILL_SCALE_RANGE: std::ops::RangeInclusive = 0.01..=20.0; /// Slider range of a UV fill's rotation, a full turn const FILL_ROTATION_DEGREES_RANGE: std::ops::RangeInclusive = 0.0..=360.0; -/// Tri-planar hardness: the exponent on the normal that weights the three projections, clamped to the same range by `layer.fill.projection` +/// Tri-planar hardness, the exponent weighting the three projections; `layer.fill.projection` clamps to the same range const TRIPLANAR_HARDNESS_RANGE: std::ops::RangeInclusive = 1.0..=64.0; -/// A fill's projection kind, axis and tri-planar hardness, then its collapsible UV transformations; each edit sends only its field -fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value) { +/// A fill's projection kind, axis and hardness, then its collapsible UV transformations +fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, salt: &str) { let projection_label = fill.projection.label(); combo(ui, tr("Projection"), tr(projection_label), |ui| { for (id, label) in [ @@ -1629,8 +1635,9 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: } }); - let mut edit = |extra: Value| { - app.run("layer.fill.projection", with(base, extra)); + // Each edit sends only the fields it changed; the command keeps the others + let mut edit = |fields: Value| { + app.run("layer.fill.projection", with(base, fields)); }; if let Projection::Planar { axis, .. } | Projection::Cylindrical { axis, .. } = &fill.projection && let Some(picked_axis) = axis_combo(ui, *axis) @@ -1638,14 +1645,14 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: edit(json!({"axis": picked_axis})); } if let Projection::Triplanar { sharpness, .. } = &fill.projection { - let mut sharpness = *sharpness; - if let Some(merge) = slider_edit(ui, tr("Hardness"), &mut sharpness, TRIPLANAR_HARDNESS_RANGE, 1) { - edit(json!({"sharpness": sharpness, "merge": merge})); + let mut hardness = *sharpness; + if let Some(merge) = slider_edit(ui, tr("Hardness"), &mut hardness, TRIPLANAR_HARDNESS_RANGE, 1) { + edit(json!({"sharpness": hardness, "merge": merge})); } } // One id per fill so each keeps its own open or closed state - section(ui, &format!("sec_fill_transform{base}"), tr("UV transformations"), true, |ui| { + section(ui, &format!("sec_fill_transform{salt}"), tr("UV transformations"), true, |ui| { projection_transform(ui, &fill.projection, &mut edit); }); } @@ -1669,13 +1676,13 @@ fn projection_transform(ui: &mut Ui, projection: &Projection, edit: &mut impl Fn if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut rotation_degrees, FILL_ROTATION_DEGREES_RANGE, 0) { edit(json!({"rotation": rotation_degrees, "merge": merge})); } - if let Some((offset, merge)) = offset_sliders(ui, ["U", "V"], *offset) { - edit(json!({"offset": offset, "merge": merge})); + if let Some((edited_offset, merge)) = offset_sliders(ui, ["U", "V"], *offset) { + edit(json!({"offset": edited_offset, "merge": merge})); } } Projection::Triplanar { offset, .. } | Projection::Planar { offset, .. } => { - if let Some((offset, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { - edit(json!({"offset": offset, "merge": merge})); + if let Some((edited_offset, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { + edit(json!({"offset": edited_offset, "merge": merge})); } } Projection::Spherical { .. } | Projection::Cylindrical { .. } | Projection::Decal(_) => {} diff --git a/crates/ui-egui/tests/fill_projection_section.rs b/crates/ui-egui/tests/fill_projection_section.rs index 3d6e2c20..983f1bc5 100644 --- a/crates/ui-egui/tests/fill_projection_section.rs +++ b/crates/ui-egui/tests/fill_projection_section.rs @@ -62,6 +62,11 @@ fn hardness_and_axis_stay_outside_the_section() { toggle_section(&mut harness); assert!(harness.query_by_label("Offset X").is_none()); assert!(harness.query_by_label("Axis").is_some()); + + let (mut harness, _) = app_with_fill("cylindrical"); + toggle_section(&mut harness); + assert!(harness.query_by_label("Scale / tiling").is_none()); + assert!(harness.query_by_label("Axis").is_some()); } #[test] @@ -79,3 +84,19 @@ fn each_fill_keeps_its_own_open_state() { harness.run_steps(SETTLE_FRAMES); assert!(harness.query_by_label("Rotation").is_none(), "the first fill stays closed"); } + +#[test] +fn a_fill_effect_keeps_a_state_apart_from_its_layer() { + let (mut harness, layer) = app_with_fill("uv"); + toggle_section(&mut harness); + + let session = &mut harness.state_mut().session; + let added = texturecraft_engine::execute(session, "effect.add.fill", &json!({"layer": layer, "target": "content"})).unwrap(); + let effect = added["effect"].as_u64().unwrap(); + texturecraft_engine::execute(session, "layer.select", &json!({"layer": layer, "target": effect})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_label("Rotation").is_some(), "the effect's section starts open"); + + toggle_section(&mut harness); + assert!(harness.query_by_label("Rotation").is_none()); +} From 49bd4a1273fdf58bb8e4954addeaa0bf7c7c8b6a Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 07:52:40 +0000 Subject: [PATCH 34/73] Polygon fill: review fixes - A box drag always finishes: on release (even after a failed move), before any edit, undo, redo or tool change, and when a scripted box fails or starts while another drag is open. A camera move mid-drag (wheel zoom) keeps the drag and selects again from the new camera. - A drag projects the mesh once, skips repaints whose box hasn't moved, and builds each grouping once; triangle edges are computed once. - 2D clicks read the triangle from the set's UV G-buffer at the clicked texel, so collapsed UV faces can't take the click. - Brush strokes no longer record the nearest-triangle buffer; only polygon fill asks for it (EyeDepth::render_with_triangles). Screen projection is shared through paint::screen_point. - A box touching the view's edge or zero-size on whole pixels selects exactly the pixels it covers. - Click fills never merge into a box drag's undo step; FillMode moves to its own file; partial box parameters get their own error. --- crates/engine/src/fill_hit_test.rs | 33 ++- crates/engine/src/fill_mode.rs | 17 ++ crates/engine/src/lib.rs | 4 +- crates/engine/src/painting.rs | 3 +- crates/engine/src/polygon_fill.rs | 367 ++++++++++++++++-------- crates/engine/src/polygon_fill_drag.rs | 23 +- crates/engine/src/session.rs | 56 ++-- crates/engine/src/tool_cmds.rs | 72 ++--- crates/engine/src/triangle_partition.rs | 20 +- crates/paint/src/lib.rs | 2 +- crates/paint/src/visibility.rs | 72 +++-- crates/ui-egui/src/viewport.rs | 13 +- crates/ui-egui/tests/polygon_fill.rs | 3 +- 13 files changed, 439 insertions(+), 246 deletions(-) create mode 100644 crates/engine/src/fill_mode.rs diff --git a/crates/engine/src/fill_hit_test.rs b/crates/engine/src/fill_hit_test.rs index 8a2b9359..b30b2452 100644 --- a/crates/engine/src/fill_hit_test.rs +++ b/crates/engine/src/fill_hit_test.rs @@ -25,17 +25,17 @@ impl FillHitTest { /// Area-weighted center of the triangles (their corners' mean when they have no area) fn center(triangles: &[[Vec2; 3]]) -> Option { - let area = |corners: &[Vec2; 3]| (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs(); - let centroid = |corners: &[Vec2; 3]| (corners[0] + corners[1] + corners[2]) / 3.0; - let total: f32 = triangles.iter().map(area).sum(); - let weighted: Vec2 = triangles.iter().map(|corners| centroid(corners) * area(corners)).sum(); - let centroids: Vec2 = triangles.iter().map(centroid).sum(); - - match triangles.len() { - 0 => None, - count if total <= f32::EPSILON => Some(centroids / count as f32), - _ => Some(weighted / total), + if triangles.is_empty() { + return None; } + + // One pass: total area, area-weighted centroids and plain centroids + let (total_area, weighted, centroids) = triangles.iter().fold((0.0, Vec2::ZERO, Vec2::ZERO), |(total_area, weighted, centroids), corners| { + let area = (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs(); + let centroid = (corners[0] + corners[1] + corners[2]) / 3.0; + (total_area + area, weighted + centroid * area, centroids + centroid) + }); + Some(if total_area > 0.0 { weighted / total_area } else { centroids / triangles.len() as f32 }) } /// Separating axis test of a triangle against an axis-aligned box @@ -63,11 +63,14 @@ mod tests { const TRIANGLE: [Vec2; 3] = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 4.0)]; #[test] - fn intersection_needs_any_overlap_and_contained_center_the_center() { - let (low, high) = (Vec2::new(2.0, 2.0), Vec2::new(6.0, 6.0)); - assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(1.0, 1.0), high), "a box cutting the triangle"); - assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(3.0, 3.0), Vec2::new(5.0, 5.0)), "inside the bounds, past the long edge"); - assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], low, high), "the center (4/3, 4/3) lies outside"); + fn intersection_selects_any_overlap() { + assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(6.0)), "a box cutting the triangle"); + assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(3.0), Vec2::splat(5.0)), "inside the bounds, past the long edge"); + } + + #[test] + fn contained_center_selects_only_by_the_center() { + assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(2.0), Vec2::splat(6.0)), "the center (4/3, 4/3) lies outside"); assert!(FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(2.0))); } diff --git a/crates/engine/src/fill_mode.rs b/crates/engine/src/fill_mode.rs new file mode 100644 index 00000000..f314562e --- /dev/null +++ b/crates/engine/src/fill_mode.rs @@ -0,0 +1,17 @@ +//! What one polygon fill target grows to. + +use serde::{Deserialize, Serialize}; + +/// Polygon fill granularity: what a clicked triangle or a boxed polygon grows to +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum FillMode { + /// The triangle itself + #[default] + Triangle, + /// The source polygon (quad or n-gon) the importer split into triangles + Polygon, + /// The UV island: triangles sharing edges in UV space + UvIsland, + /// The connected geometry: triangles sharing edges by position + Mesh, +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 824ccf48..6c6c9964 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -16,6 +16,7 @@ pub mod decal_cmds; pub mod effect_clipboard; pub mod file_cmds; pub mod fill_hit_test; +pub mod fill_mode; pub mod filter_lib; pub mod inspect; pub mod instance_cmds; @@ -55,9 +56,10 @@ pub mod view_cmds; pub use bake::{BakeMesh, BakeMeshes, BakeTask}; pub use commands::{CommandSpec, command_specs, execute, find}; pub use fill_hit_test::FillHitTest; +pub use fill_mode::FillMode; pub use path_tool::PathState; pub use project_cmds::sample_session; -pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; +pub use session::{CloneFrom, CloneSource, Document, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; pub use set_cmds::{ResizeOutput, ResizeTask}; pub use texturecraft_compose as compose; diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 86761f79..afc67a28 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -502,7 +502,8 @@ impl Session { return self.paint_fill(ts, canvas); } - self.edit(label, |session| session.paint_fill(ts, canvas)) + // Each fill is its own step, never merged into a box drag's step of the same label + self.edit_merging(label, false, |session| session.paint_fill(ts, canvas)) } /// Paint a one-shot fill with the tool's material into the paint target, or into the quick mask while it is edited (no undo step) diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs index 2d577835..a235e483 100644 --- a/crates/engine/src/polygon_fill.rs +++ b/crates/engine/src/polygon_fill.rs @@ -3,21 +3,19 @@ use std::borrow::Cow; use std::collections::{BTreeSet, HashSet}; -use texturecraft_geom::glam::{Vec2, Vec4Swizzles}; +use texturecraft_geom::glam::Vec2; use texturecraft_geom::{Mesh, NO_TRI}; -use texturecraft_paint::{EyeDepth, fill_triangles}; +use texturecraft_paint::{EyeDepth, fill_triangles, screen_point}; +use crate::fill_mode::FillMode; use crate::polygon_fill_drag::PolygonFillDrag; -use crate::session::{FillMode, Session}; +use crate::session::Session; use crate::triangle_partition::TrianglePartition; use crate::{EngineError, Result}; /// Corners closer than one step of this grid (per unit of position or UV) count as the same corner const CORNER_GRID_STEPS: f32 = 1e5; -/// Clip-space w below which a vertex counts as behind the camera -const MIN_CLIP_W: f32 = 1e-5; - impl Session { /// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen` pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { @@ -29,73 +27,131 @@ impl Session { self.fill_group_of(hit.tri) } - /// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view) + /// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view): the triangle covering that texel's center, so slivers thinner than a texel can't be clicked pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result { - let material = self.fill_material()?; - let mesh = &self.mesh; - let triangle = mesh - .triangles_of(material) - .find(|triangle| uv_corners(mesh, *triangle).is_some_and(|corners| contains(corners, uv))) + let gbuf = self.caches.get(self.ts()).map(|cache| cache.gbuf.clone()).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; + let size = Vec2::new(gbuf.width as f32, gbuf.height as f32); + let texel = (uv * size).floor(); + let triangle = (texel.cmpge(Vec2::ZERO).all() && texel.cmplt(size).all()) + .then(|| gbuf.tri.get(texel.y as usize * gbuf.width as usize + texel.x as usize).copied()) + .flatten() + .filter(|triangle| *triangle != NO_TRI) .ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; - self.fill_group_of(triangle as u32) + self.fill_group_of(triangle) } /// Fill what the box between viewport pixels `corner` and `opposite` selects (one undo step) pub fn polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result { - self.drag_polygon_fill_box(corner, opposite, viewport)?; - Ok(self.end_polygon_fill_box()) + // A scripted box stands alone: it finishes any drag under way, and ends even when it fails + self.end_polygon_fill_box(); + let shown = self.drag_polygon_fill_box(corner, opposite, viewport); + let filled = self.end_polygon_fill_box(); + shown.map(|_| filled) } /// Fill what the box between texture coordinates `corner` and `opposite` selects (the 2D view, one undo step) pub fn polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result { - self.drag_polygon_fill_box_uv(corner, opposite)?; - Ok(self.end_polygon_fill_box()) + self.end_polygon_fill_box(); + let shown = self.drag_polygon_fill_box_uv(corner, opposite); + let filled = self.end_polygon_fill_box(); + shown.map(|_| filled) } /// Show the fill of a box being dragged between viewport pixels `corner` and `opposite` pub fn drag_polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result { - let (low, high) = box_bounds(corner, opposite)?; - let viewport = viewport.max(Vec2::ONE); - self.start_polygon_fill_drag(Some(viewport))?; - - let view_proj = self.camera.view_proj(viewport.x / viewport.y); - let mesh = self.mesh.clone(); - let to_screen = |vertex: usize| { - let clip = view_proj * mesh.positions.get(vertex)?.extend(1.0); - let ndc = (clip.w > MIN_CLIP_W).then(|| clip.xy() / clip.w)?; - Some(Vec2::new(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * viewport) - }; - let screen_corners = |triangle: usize| { - let [first, second, third] = mesh.tri(triangle)?; - Some([to_screen(first)?, to_screen(second)?, to_screen(third)?]) - }; - let selected = self.box_selection(&screen_corners, low, high); - self.show_box_fill(selected) + // Whole pixels, as the visibility buffer is rendered at + self.drag_polygon_fill(corner, opposite, Some(viewport.round().max(Vec2::ONE))) } /// Show the fill of a box being dragged between texture coordinates `corner` and `opposite` (the 2D view) pub fn drag_polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result { - let (low, high) = box_bounds(corner, opposite)?; - self.start_polygon_fill_drag(None)?; - - let mesh = self.mesh.clone(); - let selected = self.box_selection(&|triangle| uv_corners(&mesh, triangle), low, high); - self.show_box_fill(selected) + self.drag_polygon_fill(corner, opposite, None) } /// Finish the dragged box: what it filled becomes one undo step. Returns the filled triangle count pub fn end_polygon_fill_box(&mut self) -> usize { let Some(drag) = self.polygon_fill_drag.take() else { return 0 }; - // Quick mask edits keep no history, as with its strokes let filled = drag.filled.len(); + // Quick mask edits keep no history, as with its strokes if filled > 0 && drag.quick_mask_before.is_none() { self.push_history("Polygon fill", drag.before); } filled } + /// Show the fill of a box from `corner` to `opposite` in the 3D view of size `viewport`, or in the 2D view when None + fn drag_polygon_fill(&mut self, corner: Vec2, opposite: Vec2, viewport: Option) -> Result { + if !corner.is_finite() || !opposite.is_finite() { + return Err(EngineError::Other("the box corners must be finite".into())); + } + + let (low, high) = (corner.min(opposite), corner.max(opposite)); + self.start_polygon_fill_drag(viewport)?; + let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) }; + + if drag.failed || drag.last_box == Some((low, high)) { + return Ok(drag.filled.len()); + } + + drag.last_box = Some((low, high)); + let selected = self.box_selection(low, high); + self.show_box_fill(selected) + } + + /// Begin a box drag unless one is under way in the same view, texture set and quick mask state; a drag from another one ends first + fn start_polygon_fill_drag(&mut self, viewport: Option) -> Result<()> { + let ts = self.ts(); + let quick_mask = self.quick_mask.editing; + // A different view size, set or quick mask state starts a new drag; the old one keeps its fill as one step + if let Some(drag) = &self.polygon_fill_drag { + if drag.ts == ts && drag.viewport == viewport && drag.quick_mask_before.is_some() == quick_mask { + // A camera move (a wheel zoom mid-drag) keeps the drag, which then sees the mesh from the new camera + if drag.camera != self.camera { + let (points, depth) = self.box_space(viewport); + if let Some(drag) = self.polygon_fill_drag.as_mut() { + (drag.points, drag.depth, drag.camera, drag.last_box) = (points, depth, self.camera, None); + } + } + return Ok(()); + } + self.end_polygon_fill_box(); + } + + let material = self.fill_material()?; + let (points, depth) = self.box_space(viewport); + let polygons = match self.tool.fill_mode { + FillMode::Triangle | FillMode::Polygon => None, + FillMode::UvIsland | FillMode::Mesh => Some(TrianglePartition::new(&self.mesh, material, polygon_edges)), + }; + self.polygon_fill_drag = Some(PolygonFillDrag { + ts, + viewport, + camera: self.camera, + before: self.doc.clone(), + quick_mask_before: quick_mask.then(|| self.quick_mask.masks.clone()), + points, + depth, + fill_groups: self.fill_partition(material), + polygons, + filled: BTreeSet::new(), + last_box: None, + failed: false, + }); + Ok(()) + } + + /// Each vertex where a box sees it (viewport pixels for a 3D view of size `viewport`, else texture coordinates) and, for visible polygons only in 3D, what the camera sees + fn box_space(&self, viewport: Option) -> (Vec>, Option) { + let Some(size) = viewport else { return (self.mesh.uvs.iter().copied().map(Some).collect(), None) }; + + let view_proj = self.camera.view_proj(size.x / size.y); + let points = self.mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect(); + let depth = self.tool.fill_visible_only.then(|| EyeDepth::render_with_triangles(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32)); + (points, depth) + } + /// The mesh material of the texture set being painted fn fill_material(&self) -> Result { Ok(self.doc.project.texture_set(self.ts())?.material) @@ -123,32 +179,6 @@ impl Session { Ok(triangles.len()) } - /// Begin a box drag unless one is under way; `viewport` is the 3D view's size (None in the 2D view) - fn start_polygon_fill_drag(&mut self, viewport: Option) -> Result<()> { - if self.polygon_fill_drag.is_some() { - return Ok(()); - } - - let material = self.fill_material()?; - let polygons = match self.tool.fill_mode { - FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::::new()), - _ => TrianglePartition::new(&self.mesh, material, polygon_edges), - }; - let depth = viewport - .filter(|_| self.tool.fill_visible_only) - .map(|size| (EyeDepth::render(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32), size)); - self.polygon_fill_drag = Some(PolygonFillDrag { - before: self.doc.clone(), - quick_mask_before: self.quick_mask.editing.then(|| self.quick_mask.masks.clone()), - filled: BTreeSet::new(), - depth, - polygons, - fill_groups: self.fill_partition(material), - failed: false, - }); - Ok(()) - } - /// The mesh as the 3D view shows it: hidden texture sets' triangles collapse to a point, so nothing behind them counts as hidden fn shown_mesh(&self) -> Cow<'_, Mesh> { let sets = &self.doc.project.texture_sets; @@ -168,17 +198,28 @@ impl Session { Cow::Owned(mesh) } - /// Triangles the dragged box from `low` to `high` fills, given each triangle's `corners` in the box's space - fn box_selection(&self, corners: &dyn Fn(usize) -> Option<[Vec2; 3]>, low: Vec2, high: Vec2) -> BTreeSet { + /// Triangles the dragged box from `low` to `high` fills: each polygon the hit-test selects, grown by the fill mode + fn box_selection(&self, low: Vec2, high: Vec2) -> BTreeSet { let Some(drag) = &self.polygon_fill_drag else { return BTreeSet::new() }; - let visible = drag.depth.as_ref().map(|(depth, viewport)| visible_triangles(depth, *viewport, low, high)); + let visible = drag.depth.as_ref().zip(drag.viewport).map(|(depth, viewport)| visible_triangles(depth, viewport, low, high)); + let point = |vertex: usize| drag.points.get(vertex).copied().flatten(); + let corners = |triangle: u32| { + let [first, second, third] = self.mesh.tri(triangle as usize)?; + Some([point(first)?, point(second)?, point(third)?]) + }; let hit_test = self.tool.fill_hit_test; + let mut polygon_corners = Vec::new(); let mut groups = BTreeSet::new(); - for polygon in &drag.polygons.groups { + for polygon in &drag.polygons.as_ref().unwrap_or(&drag.fill_groups).groups { let seen = visible.as_ref().is_none_or(|visible| polygon.iter().any(|triangle| visible.contains(triangle))); - let triangles: Option> = polygon.iter().map(|triangle| corners(*triangle as usize)).collect(); - if seen && triangles.is_some_and(|triangles| hit_test.selects(&triangles, low, high)) { + if !seen { + continue; + } + + polygon_corners.clear(); + polygon_corners.extend(polygon.iter().map_while(|triangle| corners(*triangle))); + if polygon_corners.len() == polygon.len() && hit_test.selects(&polygon_corners, low, high) { groups.extend(polygon.iter().filter_map(|triangle| drag.fill_groups.index_of(*triangle))); } } @@ -189,17 +230,17 @@ impl Session { /// Show the box drag's fill of `selected`: the document before the drag, refilled when the selection changed fn show_box_fill(&mut self, selected: BTreeSet) -> Result { let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) }; - if drag.failed || drag.filled == selected { - return Ok(drag.filled.len()); + if drag.filled == selected { + return Ok(selected.len()); } - drag.filled = selected.clone(); + let ts = drag.ts; let previous = std::mem::replace(&mut self.doc, drag.before.clone()); if let Some(masks) = &drag.quick_mask_before { self.quick_mask.masks = masks.clone(); + self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); } - let ts = self.ts(); let painted = if selected.is_empty() { Ok(()) } else { @@ -209,37 +250,23 @@ impl Session { }) }; self.invalidate_changed(&previous); - self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); - // A failed fill is reported once; the rest of the drag fills nothing - if painted.is_err() - && let Some(mut drag) = self.polygon_fill_drag.take() - { - self.restore_before_box(&drag); - drag.failed = true; - drag.filled.clear(); - self.polygon_fill_drag = Some(drag); + // A failed fill is reported once and leaves the document as before the drag; the rest of the drag fills nothing + let selected_count = selected.len(); + if let Some(drag) = self.polygon_fill_drag.as_mut() { + drag.failed = painted.is_err(); + drag.filled = if drag.failed { BTreeSet::new() } else { selected }; } - painted.map(|_| selected.len()) - } - - /// Put back the document and quick mask from before the box `drag` - fn restore_before_box(&mut self, drag: &PolygonFillDrag) { - let previous = std::mem::replace(&mut self.doc, drag.before.clone()); - if let Some(masks) = &drag.quick_mask_before { - self.quick_mask.masks = masks.clone(); - self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); - } - self.invalidate_changed(&previous); + painted.map(|_| selected_count) } } -/// Triangles `depth` (rendered for `viewport`) shows in the viewport pixels from `low` to `high` +/// Triangles `depth` (rendered for a `viewport` pixel view) shows in the viewport pixels from `low` to `high`, both edges included fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> HashSet { - let pixels_per_point = Vec2::new(depth.width as f32, depth.height as f32) / viewport; - let (first, last) = ((low * pixels_per_point).floor(), (high * pixels_per_point).ceil()); - let columns = first.x.max(0.0) as usize..(last.x as usize).min(depth.width as usize); - let rows = first.y.max(0.0) as usize..(last.y as usize).min(depth.height as usize); + let depth_pixels_per_viewport_pixel = Vec2::new(depth.width as f32, depth.height as f32) / viewport; + let (low, high) = (low * depth_pixels_per_viewport_pixel, high * depth_pixels_per_viewport_pixel); + let columns = pixel_span(low.x, high.x, depth.width); + let rows = pixel_span(low.y, high.y, depth.height); rows.flat_map(|row| depth.triangle.get(row * depth.width as usize..).into_iter().flat_map(|pixels| pixels.iter().take(columns.end).skip(columns.start))) .copied() @@ -247,13 +274,11 @@ fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> .collect() } -/// The two corners spanning a box, lowest first -fn box_bounds(corner: Vec2, opposite: Vec2) -> Result<(Vec2, Vec2)> { - if !corner.is_finite() || !opposite.is_finite() { - return Err(EngineError::Other("the box corners must be finite".into())); - } - - Ok((corner.min(opposite), corner.max(opposite))) +/// The pixels `0..count` a span from `low` to `high` covers, both edges included (empty when it lies outside) +fn pixel_span(low: f32, high: f32, count: u32) -> std::ops::Range { + let first = low.floor().clamp(0.0, count as f32) as usize; + let end = (high.floor() + 1.0).clamp(0.0, count as f32) as usize; + first..end.max(first) } /// Texture coordinates of `triangle`'s corners @@ -262,13 +287,6 @@ fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> { Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?]) } -/// Whether `point` lies in the triangle with `corners` (either winding) -fn contains(corners: [Vec2; 3], point: Vec2) -> bool { - let side = |edge: usize| (corners[(edge + 1) % 3] - corners[edge]).perp_dot(point - corners[edge]); - let sides = [side(0), side(1), side(2)]; - sides.iter().all(|side| *side >= 0.0) || sides.iter().all(|side| *side <= 0.0) -} - /// The polygon diagonals of `triangle`: edges the importer added to split a polygon fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> { let hidden = mesh.diagonals.get(triangle).copied().unwrap_or(0); @@ -308,7 +326,8 @@ mod tests { use texturecraft_geom::primitives; use crate::fill_hit_test::FillHitTest; - use crate::session::{FillMode, Session, Tool}; + use crate::fill_mode::FillMode; + use crate::session::{Session, Tool}; /// The roughness the test fills paint, to tell filled texels apart const FILL_ROUGHNESS: f32 = 0.9; @@ -446,6 +465,44 @@ mod tests { assert!(!filled_at(&session, Vec2::new(0.2, 0.5)), "one undo removes the whole drag"); } + #[test] + fn a_failed_box_fill_leaves_no_drag_behind() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let layer = session.selected.remove(&0).unwrap(); + assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).is_err(), "no layer to paint on"); + + session.selected.insert(0, layer); + assert_eq!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32, "the next box fills again"); + } + + #[test] + fn undo_and_tool_changes_finish_a_box_drag_first() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let history = session.history_labels().len(); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + assert_eq!(session.undo().unwrap(), "Polygon fill", "undo takes back the drag it finished"); + assert!(session.polygon_fill_drag.is_none()); + assert_eq!(session.history_labels().len(), history); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + crate::tool_cmds::set_tool(&mut session, Tool::Paint).unwrap(); + assert!(session.polygon_fill_drag.is_none()); + assert_eq!(session.history_labels().len(), history + 1, "a tool change keeps the fill as one step"); + } + + #[test] + fn an_unmoved_box_keeps_its_fill() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let narrow_box = Vec2::new(0.3, 1.0); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "intersection: the two columns the box touches"); + + // Contained center would select one column, so a second selection would show 8 + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "the same box selects nothing again"); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box + Vec2::new(0.01, 0.0)).unwrap(), 8, "a moved box selects again"); + } + #[test] fn a_uv_box_over_the_second_uv_tile_fills_that_tile_only() { let mut session = fill_session(primitives::udim_plane()); @@ -456,6 +513,82 @@ mod tests { assert_eq!(session.polygon_fill_box_uv(Vec2::new(0.5, 0.0), Vec2::ONE).unwrap(), every_triangle / 2, "the atlas's right half is tile 1002"); } + #[test] + fn a_2d_click_skips_a_triangle_with_collapsed_uvs() { + // A face left unmapped (all corners at UV 0,0) comes first, as imports often leave them + let plane = primitives::plane(2.0, 1); + let mut positions = vec![Vec3::ZERO, Vec3::X, Vec3::Z]; + let mut uvs = vec![Vec2::ZERO; 3]; + positions.extend(&plane.positions); + uvs.extend(&plane.uvs); + let indices = [0, 1, 2].into_iter().chain(plane.indices.iter().map(|index| index + 3)).collect(); + let mut session = fill_session(Mesh::from_parts(positions, None, uvs, indices, "m").unwrap()); + + assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1); + session.update(); + assert!(filled_at(&session, Vec2::new(0.2, 0.7)), "the triangle under the cursor, not the collapsed one"); + } + + #[test] + fn a_failing_drag_reports_once_and_records_nothing() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let history = session.history_labels().len(); + session.selected.clear(); + + assert!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.5, 1.0)).is_err()); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 0, "the rest of the drag fills nothing"); + assert_eq!(session.end_polygon_fill_box(), 0); + assert_eq!(session.history_labels().len(), history); + } + + #[test] + fn an_edit_during_a_drag_records_the_fill_first() { + let mut session = fill_session(primitives::plane(2.0, 4)); + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + + let layers = session.doc.project.layers.len(); + crate::execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + assert!(session.polygon_fill_drag.is_none()); + let labels = session.history_labels(); + assert_eq!(labels.get(labels.len().wrapping_sub(2)).map(String::as_str), Some("Polygon fill"), "{labels:?}"); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap(); + assert_eq!(session.doc.project.layers.len(), layers + 1, "a later drag move keeps the added layer"); + } + + #[test] + fn a_zero_size_box_on_whole_pixels_selects_what_is_under_it() { + let mut session = fill_session(primitives::cube(1.0)); + let center = (session.viewport * 0.5).floor(); + + assert!(session.polygon_fill_box(center, center, session.viewport).unwrap() > 0); + } + + #[test] + fn a_camera_move_mid_drag_keeps_one_drag() { + let mut session = fill_session(primitives::cube(1.0)); + let viewport = session.viewport; + let history = session.history_labels().len(); + + let (corner, opposite) = (viewport * 0.4, viewport * 0.6); + + let before_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap(); + session.camera.zoom(0.5); + let after_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap(); + session.end_polygon_fill_box(); + + assert_ne!(before_zoom, after_zoom, "the same box selects again from the new camera"); + assert_eq!(session.history_labels().len(), history + 1, "a wheel zoom during the drag doesn't split it"); + } + + #[test] + fn pixel_spans_include_both_edges_and_nothing_outside() { + assert_eq!(super::pixel_span(2.0, 2.0, 100), 2..3, "a zero-size span on a whole pixel"); + assert_eq!(super::pixel_span(-50.0, -10.0, 100), 0..0, "before the first pixel"); + assert_eq!(super::pixel_span(120.0, 150.0, 100), 100..100, "past the last pixel"); + assert_eq!(super::pixel_span(-5.0, 500.0, 100), 0..100); + } + #[test] fn a_2d_click_fills_the_triangle_under_it() { let mut session = fill_session(primitives::plane(2.0, 1)); diff --git a/crates/engine/src/polygon_fill_drag.rs b/crates/engine/src/polygon_fill_drag.rs index 4a7bc104..f4457e55 100644 --- a/crates/engine/src/polygon_fill_drag.rs +++ b/crates/engine/src/polygon_fill_drag.rs @@ -2,6 +2,7 @@ use std::collections::{BTreeMap, BTreeSet}; +use texturecraft_geom::OrbitCamera; use texturecraft_geom::glam::Vec2; use texturecraft_paint::EyeDepth; use texturecraft_texel::TileImage; @@ -11,18 +12,28 @@ use crate::triangle_partition::TrianglePartition; /// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends pub(crate) struct PolygonFillDrag { + /// The texture set it fills + pub ts: usize, + /// The 3D view's size in pixels, or None for a drag in the 2D view + pub viewport: Option, + /// The camera [`PolygonFillDrag::points`] and [`PolygonFillDrag::depth`] were made with + pub camera: OrbitCamera, /// The document before the drag, refilled each time the selection changes pub before: Document, /// The quick mask's coverage before the drag, when the drag paints the quick mask pub quick_mask_before: Option>, - /// The triangles filled so far - pub filled: BTreeSet, - /// What the camera sees and the viewport size it was rendered for (3D view, visible polygons only) - pub depth: Option<(EyeDepth, Vec2)>, - /// The polygons the box tests - pub polygons: TrianglePartition, + /// Each vertex where the box sees it: viewport pixels in the 3D view (None behind the camera), texture coordinates in the 2D view + pub points: Vec>, + /// What the camera sees (3D view, visible polygons only) + pub depth: Option, /// What the fill mode fills together pub fill_groups: TrianglePartition, + /// The polygons the box tests, when they differ from the fill groups + pub polygons: Option, + /// The triangles filled so far + pub filled: BTreeSet, + /// The box last shown, lowest corner first: an unmoved box isn't selected again + pub last_box: Option<(Vec2, Vec2)>, /// The fill failed (reported once): the rest of the drag fills nothing pub failed: bool, } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index c5b55649..c6b7c469 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -11,6 +11,7 @@ use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer}; use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas}; use texturecraft_texel::DilationMap; +use crate::fill_mode::FillMode; use crate::{EngineError, Result}; /// Padding (texels) applied to composites for display. @@ -160,17 +161,6 @@ impl ViewMode { } } -/// Polygon fill granularity. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum FillMode { - #[default] - Triangle, - /// The source polygon (quad or n-gon) the importer split into triangles - Polygon, - UvIsland, - Mesh, -} - /// A screen-pinned image for the Projection tool (a stencil). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StencilState { @@ -506,22 +496,24 @@ impl Session { self.edit_merging(label, self.merge_edits, f) } - /// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the - /// same label (a drag in the viewport is one step however many updates it makes). - pub fn edit_merging(&mut self, label: &str, merge: bool, f: impl FnOnce(&mut Session) -> Result) -> Result { + /// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the same label (a viewport drag is one step however many updates it makes). + pub fn edit_merging(&mut self, label: &str, merge: bool, change: impl FnOnce(&mut Session) -> Result) -> Result { + // A box fill under way becomes its own step first, so this edit isn't written over or folded into it + self.end_polygon_fill_box(); + let before = self.doc.clone(); - let result = f(self).and_then(|v| match self.doc.project.instance_cycle() { + let result = change(self).and_then(|value| match self.doc.project.instance_cycle() { Some(id) => Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))), - None => Ok(v), + None => Ok(value), }); match result { - Ok(v) => { + Ok(value) => { self.record(label, before, merge); - Ok(v) + Ok(value) } - Err(e) => { + Err(error) => { self.doc = before; - Err(e) + Err(error) } } } @@ -642,25 +634,29 @@ impl Session { } pub fn undo(&mut self) -> Result { + // A stroke, a box fill or an edited path under way would otherwise write over the restored document self.cancel_stroke(); - // An edited path would otherwise repaint over the restored document. + self.end_polygon_fill_box(); self.stop_path_edit(); - let (label, doc) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; - let now = std::mem::replace(&mut self.doc, doc); - self.after_history(&now); - self.redo.push((label.clone(), now)); + + let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; + let current = std::mem::replace(&mut self.doc, restored); + self.after_history(¤t); + self.redo.push((label.clone(), current)); self.sync_images(); Ok(label) } pub fn redo(&mut self) -> Result { + // A stroke, a box fill or an edited path under way would otherwise write over the restored document self.cancel_stroke(); - // An edited path would otherwise repaint over the restored document. + self.end_polygon_fill_box(); self.stop_path_edit(); - let (label, doc) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; - let now = std::mem::replace(&mut self.doc, doc); - self.after_history(&now); - self.undo.push((label.clone(), now)); + + let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; + let current = std::mem::replace(&mut self.doc, restored); + self.after_history(¤t); + self.undo.push((label.clone(), current)); self.sync_images(); Ok(label) } diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index ba7f0f9b..a3f92bba 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -8,7 +8,8 @@ use texturecraft_paint::{Alignment, BrushAlpha, alphas}; use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp}; use crate::fill_hit_test::FillHitTest; -use crate::session::{CloneFrom, CloneSource, FillMode, Tool}; +use crate::fill_mode::FillMode; +use crate::session::{CloneFrom, CloneSource, Tool}; use crate::{Result, Session, cmd}; pub fn specs() -> Vec { @@ -103,11 +104,13 @@ pub fn specs() -> Vec { ] } -pub(crate) fn set_tool(s: &mut Session, t: Tool) -> Result { - s.cancel_stroke(); - s.tool.tool = t; - s.revision = s.revision.wrapping_add(1); - Ok(json!({ "tool": t.id() })) +pub(crate) fn set_tool(session: &mut Session, tool: Tool) -> Result { + session.cancel_stroke(); + // A box fill under way keeps what it filled as one undo step + session.end_polygon_fill_box(); + session.tool.tool = tool; + session.revision = session.revision.wrapping_add(1); + Ok(json!({ "tool": tool.id() })) } fn select(s: &mut Session, p: &Value) -> Result { @@ -337,26 +340,27 @@ fn clone_source(s: &mut Session, p: &Value) -> Result { Ok(serde_json::to_value(s.tool.clone_source).unwrap_or(Value::Null)) } -fn fill_mode(s: &mut Session, p: &Value) -> Result { - s.tool.fill_mode = match strp(p, "mode").unwrap_or("triangle") { +fn fill_mode(session: &mut Session, params: &Value) -> Result { + session.tool.fill_mode = match strp(params, "mode").unwrap_or("triangle") { "triangle" => FillMode::Triangle, "polygon" => FillMode::Polygon, "uvIsland" | "island" => FillMode::UvIsland, "mesh" => FillMode::Mesh, other => return Err(bad("tool.fillMode", format!("unknown fill mode `{other}`"))), }; + Ok(Value::Null) } -fn fill_selection(s: &mut Session, p: &Value) -> Result { - match strp(p, "hitTest") { +fn fill_selection(session: &mut Session, params: &Value) -> Result { + match strp(params, "hitTest") { None => {} - Some("intersection") => s.tool.fill_hit_test = FillHitTest::Intersection, - Some("containedCenter") => s.tool.fill_hit_test = FillHitTest::ContainedCenter, + Some("intersection") => session.tool.fill_hit_test = FillHitTest::Intersection, + Some("containedCenter") => session.tool.fill_hit_test = FillHitTest::ContainedCenter, Some(other) => return Err(bad("tool.fillSelection", format!("unknown hit-test `{other}` (intersection or containedCenter)"))), } - if let Some(visible_only) = boolp(p, "visibleOnly") { - s.tool.fill_visible_only = visible_only; + if let Some(visible_only) = boolp(params, "visibleOnly") { + session.tool.fill_visible_only = visible_only; } Ok(Value::Null) @@ -402,38 +406,42 @@ fn stroke(s: &mut Session, p: &Value) -> Result { Ok(json!({ "stamps": stamps })) } -fn click(s: &mut Session, p: &Value) -> Result { - if s.tool.tool == Tool::PolygonFill - && let Some(triangles) = polygon_fill_click(s, p)? +fn click(session: &mut Session, params: &Value) -> Result { + if session.tool.tool == Tool::PolygonFill + && let Some(triangles) = polygon_fill_click(session, params)? { - s.update(); + session.update(); return Ok(json!({ "triangles": triangles })); } - let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) }; + let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) }; let point = Vec2::new(x, y); - let viewport = viewport_of(s, p); - let out = match s.tool.tool { - Tool::PolygonFill => json!({ "triangles": s.polygon_fill(point, viewport)? }), + let viewport = viewport_of(session, params); + let out = match session.tool.tool { + Tool::PolygonFill => json!({ "triangles": session.polygon_fill(point, viewport)? }), Tool::ColorPicker => { - let picked = s.color_pick(point, viewport)?; + let picked = session.color_pick(point, viewport)?; json!(picked.iter().map(|(channel, value)| (channel.id().to_string(), json!(value))).collect::>()) } - Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, point, viewport)?, - _ => json!({ "stamps": s.stroke_points(&[point], viewport)? }), + Tool::GeometryMask => crate::instance_cmds::toggle_part_at(session, point, viewport)?, + _ => json!({ "stamps": session.stroke_points(&[point], viewport)? }), }; - s.update(); + session.update(); Ok(out) } /// The polygon fill forms of `tool.click` besides a plain `{x, y}` point: None for that point -fn polygon_fill_click(s: &mut Session, p: &Value) -> Result> { - let screen_box = (f32p(p, "x0"), f32p(p, "y0"), f32p(p, "x1"), f32p(p, "y1")); - let filled = match (pair(p, "uv0"), pair(p, "uv1"), pair(p, "uv"), screen_box) { - (Some(corner), Some(opposite), ..) => s.polygon_fill_box_uv(corner.into(), opposite.into())?, - (_, _, Some(uv), _) => s.polygon_fill_uv(uv.into())?, - (.., (Some(x0), Some(y0), Some(x1), Some(y1))) => s.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(s, p))?, +fn polygon_fill_click(session: &mut Session, params: &Value) -> Result> { + let screen_box = (f32p(params, "x0"), f32p(params, "y0"), f32p(params, "x1"), f32p(params, "y1")); + let given = |keys: &[&str]| keys.iter().any(|key| params.get(*key).is_some()); + let filled = match (pair(params, "uv0"), pair(params, "uv1"), pair(params, "uv"), screen_box) { + (Some(corner), Some(opposite), ..) => session.polygon_fill_box_uv(corner.into(), opposite.into())?, + _ if given(&["uv0", "uv1"]) => return Err(bad("tool.click", "a UV box needs `uv0` and `uv1` as [u, v]")), + (_, _, Some(uv), _) => session.polygon_fill_uv(uv.into())?, + _ if given(&["uv"]) => return Err(bad("tool.click", "a 2D view point needs `uv` as [u, v]")), + (.., (Some(x0), Some(y0), Some(x1), Some(y1))) => session.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(session, params))?, + _ if given(&["x0", "y0", "x1", "y1"]) => return Err(bad("tool.click", "a screen box needs numbers `x0`, `y0`, `x1` and `y1`")), _ => return Ok(None), }; diff --git a/crates/engine/src/triangle_partition.rs b/crates/engine/src/triangle_partition.rs index 1364fe69..bd137e35 100644 --- a/crates/engine/src/triangle_partition.rs +++ b/crates/engine/src/triangle_partition.rs @@ -1,6 +1,7 @@ //! Triangles of one material grouped into the pieces polygon fill selects and fills. -use std::collections::{BTreeMap, HashMap}; +use std::collections::HashMap; +use std::hash::Hash; use texturecraft_geom::Mesh; @@ -14,12 +15,15 @@ pub struct TrianglePartition { impl TrianglePartition { /// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both - pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { + pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { + // Each triangle's edges once, in mesh order so the groups come out the same every time let triangles: Vec = mesh.triangles_of(material).map(|triangle| triangle as u32).collect(); - let mut by_edge: BTreeMap> = BTreeMap::new(); - for &triangle in &triangles { - for edge in edges(mesh, triangle as usize) { - by_edge.entry(edge).or_default().push(triangle); + let position_of: HashMap = triangles.iter().enumerate().map(|(position, triangle)| (*triangle, position)).collect(); + let mut edge_lists: Vec> = triangles.iter().map(|triangle| edges(mesh, *triangle as usize)).collect(); + let mut by_edge: HashMap> = HashMap::new(); + for (triangle, triangle_edges) in triangles.iter().zip(&edge_lists) { + for edge in triangle_edges { + by_edge.entry(edge.clone()).or_default().push(*triangle); } } @@ -29,12 +33,14 @@ impl TrianglePartition { if group_of.contains_key(&start) { continue; } + let mut members = Vec::new(); let mut stack = vec![start]; group_of.insert(start, groups.len()); while let Some(triangle) = stack.pop() { members.push(triangle); - for neighbour in edges(mesh, triangle as usize).iter().flat_map(|edge| by_edge.get(edge).into_iter().flatten()) { + let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default(); + for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.get(edge).into_iter().flatten()) { if !group_of.contains_key(neighbour) { group_of.insert(*neighbour, groups.len()); stack.push(*neighbour); diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index c34415ed..307ccd7f 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -29,4 +29,4 @@ pub use path::{Lasso, spline}; pub use pickup::{Pickup, PickupMode}; pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv}; pub use stroke::{PickCtx, Stamp, Stroke, SurfaceHit, pick}; -pub use visibility::EyeDepth; +pub use visibility::{EyeDepth, screen_point}; diff --git a/crates/paint/src/visibility.rs b/crates/paint/src/visibility.rs index e914d297..c2921979 100644 --- a/crates/paint/src/visibility.rs +++ b/crates/paint/src/visibility.rs @@ -2,7 +2,7 @@ //! rendered once at the start of a stroke. use rayon::prelude::*; -use texturecraft_geom::glam::{Mat4, Vec3, Vec4}; +use texturecraft_geom::glam::{Mat4, Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, OrbitCamera}; const BAND: usize = 16; @@ -11,7 +11,7 @@ const BAND: usize = 16; const MAX_SIZE: u32 = 4096; /// Clip-space w below which a vertex counts as behind the camera. -const MIN_CLIP_W: f32 = 1e-5; +pub const MIN_CLIP_W: f32 = 1e-5; /// Screen area (pixels squared) below which a triangle is skipped as degenerate. const MIN_SCREEN_AREA: f32 = 1e-9; @@ -30,28 +30,38 @@ pub struct EyeDepth { pub view_proj: Mat4, pub eye: Vec3, pub dist: Vec, - /// The nearest triangle per screen pixel ([`NO_TRI`] where empty). + /// The nearest triangle per screen pixel ([`NO_TRI`] where empty); empty unless rendered with [`EyeDepth::render_with_triangles`]. pub triangle: Vec, /// Tolerance in world units (≈ 0.4% of the scene radius). pub bias: f32, } +/// Where `position` lands in a `size` pixel view through `view_proj` (origin top-left), or None behind the camera. +pub fn screen_point(view_proj: Mat4, position: Vec3, size: Vec2) -> Option { + let clip = view_proj * position.extend(1.0); + (clip.w > MIN_CLIP_W).then(|| Vec2::new(clip.x / clip.w * 0.5 + 0.5, 0.5 - clip.y / clip.w * 0.5) * size) +} + impl EyeDepth { - /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]). + /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]), without [`EyeDepth::triangle`]. pub fn render(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth { + Self::rasterize(mesh, camera, width, height, false) + } + + /// [`EyeDepth::render`] that also records the nearest triangle per pixel in [`EyeDepth::triangle`]. + pub fn render_with_triangles(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth { + Self::rasterize(mesh, camera, width, height, true) + } + + /// The eye-distance buffer, plus the nearest triangle per pixel when `record_triangles` is set. + fn rasterize(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32, record_triangles: bool) -> EyeDepth { let (width, height) = (width.clamp(1, MAX_SIZE), height.clamp(1, MAX_SIZE)); - let view_proj = camera.view_proj(width as f32 / height as f32); + let size = Vec2::new(width as f32, height as f32); + let view_proj = camera.view_proj(size.x / size.y); let eye = camera.eye(); // Project every vertex once - let screen: Vec> = mesh - .positions - .iter() - .map(|position| { - let clip: Vec4 = view_proj * position.extend(1.0); - (clip.w > MIN_CLIP_W).then(|| ((clip.x / clip.w * 0.5 + 0.5) * width as f32, (0.5 - clip.y / clip.w * 0.5) * height as f32)) - }) - .collect(); + let screen: Vec> = mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect(); let vertex_distance: Vec = mesh.positions.iter().map(|position| position.distance(eye)).collect(); // Bin each triangle into the bands of rows it covers @@ -60,8 +70,8 @@ impl EyeDepth { let Some([first, second, third]) = mesh.tri(triangle) else { continue }; let (Some(Some(first)), Some(Some(second)), Some(Some(third))) = (screen.get(first), screen.get(second), screen.get(third)) else { continue }; - let top = first.1.min(second.1).min(third.1).floor().max(0.0); - let bottom = first.1.max(second.1).max(third.1).ceil().min(height as f32); + let top = first.y.min(second.y).min(third.y).floor().max(0.0); + let bottom = first.y.max(second.y).max(third.y).ceil().min(size.y); if bottom <= top || !top.is_finite() || !bottom.is_finite() { continue; } @@ -72,9 +82,11 @@ impl EyeDepth { } let mut dist = vec![f32::MAX; (width * height) as usize]; - let mut triangle = vec![NO_TRI; (width * height) as usize]; + let mut triangle = if record_triangles { vec![NO_TRI; (width * height) as usize] } else { Vec::new() }; let band_len = BAND * width as usize; - dist.par_chunks_mut(band_len).zip(triangle.par_chunks_mut(band_len)).enumerate().for_each(|(band, (band_dist, band_triangles))| { + let mut triangle_bands: Vec> = triangle.chunks_mut(band_len).map(Some).collect(); + triangle_bands.resize_with(dist.len().div_ceil(band_len), || None); + dist.par_chunks_mut(band_len).zip(triangle_bands.into_par_iter()).enumerate().for_each(|(band, (band_dist, mut band_triangles))| { let first_row = band * BAND; let row_count = band_dist.len() / width as usize; for &candidate in bands.get(band).map(Vec::as_slice).unwrap_or(&[]) { @@ -84,24 +96,22 @@ impl EyeDepth { else { continue; }; - let corner_distance = corners.map(|vertex| vertex_distance[vertex]); - let area = - (second_point.0 - first_point.0) * (third_point.1 - first_point.1) - (second_point.1 - first_point.1) * (third_point.0 - first_point.0); + + let corner_distance = corners.map(|vertex| vertex_distance.get(vertex).copied().unwrap_or(f32::MAX)); + let area = (*second_point - *first_point).perp_dot(*third_point - *first_point); if area.abs() < MIN_SCREEN_AREA { continue; } - let left = first_point.0.min(second_point.0).min(third_point.0).floor().max(0.0) as usize; - let right = (first_point.0.max(second_point.0).max(third_point.0).ceil().min(width as f32)) as usize; - let top = (first_point.1.min(second_point.1).min(third_point.1).floor().max(first_row as f32)) as usize; - let bottom = (first_point.1.max(second_point.1).max(third_point.1).ceil().min((first_row + row_count) as f32)) as usize; + let low = first_point.min(*second_point).min(*third_point).floor(); + let high = first_point.max(*second_point).max(*third_point).ceil(); + let (left, right) = (low.x.max(0.0) as usize, (high.x.min(size.x) as usize).min(width as usize)); + let (top, bottom) = (low.y.max(first_row as f32) as usize, high.y.min((first_row + row_count) as f32) as usize); for row in top.max(first_row)..bottom { - for column in left..right.min(width as usize) { - let (sample_x, sample_y) = (column as f32 + 0.5, row as f32 + 0.5); - let first_weight = - ((second_point.0 - sample_x) * (third_point.1 - sample_y) - (second_point.1 - sample_y) * (third_point.0 - sample_x)) / area; - let second_weight = - ((third_point.0 - sample_x) * (first_point.1 - sample_y) - (third_point.1 - sample_y) * (first_point.0 - sample_x)) / area; + for column in left..right { + let sample = Vec2::new(column as f32 + 0.5, row as f32 + 0.5); + let first_weight = (*third_point - *second_point).perp_dot(sample - *second_point) / area; + let second_weight = (*first_point - *third_point).perp_dot(sample - *third_point) / area; let third_weight = 1.0 - first_weight - second_weight; if first_weight < -EDGE_TOLERANCE || second_weight < -EDGE_TOLERANCE || third_weight < -EDGE_TOLERANCE { continue; @@ -113,7 +123,7 @@ impl EyeDepth { && distance < *slot { *slot = distance; - if let Some(nearest) = band_triangles.get_mut(at) { + if let Some(nearest) = band_triangles.as_deref_mut().and_then(|triangles| triangles.get_mut(at)) { *nearest = candidate; } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 91f816e9..491aed10 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -214,13 +214,13 @@ fn shade(app: &TextureCraftApp) -> Shade { let set_index = app.session.ts(); let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); // Polygon fill shows the polygons it fills without changing the saved wireframe toggles - let polygon_fill = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill; + let polygon_fill_tool = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, view_mode, channel, - wireframe: app.ui.uv_wireframe || polygon_fill, - wireframe_3d: app.ui.wireframe_3d || polygon_fill, + wireframe: app.ui.uv_wireframe || polygon_fill_tool, + wireframe_3d: app.ui.wireframe_3d || polygon_fill_tool, ..Shade::from_project(&app.session.doc.project) } } @@ -1040,7 +1040,12 @@ fn polygon_fill_input( let pointer = ui.input(|input| input.pointer.latest_pos()); let (filled, dragged_box) = match (origin, pointer) { _ if response.clicked_by(PointerButton::Primary) => (response.interact_pointer_pos().map(|point| fill_at(&mut app.session, point)), None), - (Some(origin), Some(pointer)) if released => (Some(drag_box(&mut app.session, origin, pointer).map(|_| app.session.end_polygon_fill_box())), None), + (Some(origin), Some(pointer)) if released => { + // The drag ends on release even when its last move failed + let shown = drag_box(&mut app.session, origin, pointer); + let filled = app.session.end_polygon_fill_box(); + (Some(shown.map(|_| filled)), None) + } (Some(origin), Some(pointer)) => (Some(drag_box(&mut app.session, origin, pointer)), Some(Rect::from_two_pos(origin, pointer))), _ => (None, None), }; diff --git a/crates/ui-egui/tests/polygon_fill.rs b/crates/ui-egui/tests/polygon_fill.rs index dc007035..313ad184 100644 --- a/crates/ui-egui/tests/polygon_fill.rs +++ b/crates/ui-egui/tests/polygon_fill.rs @@ -27,8 +27,9 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { harness.run_steps(1); } + // Only the release frame runs, so the release itself must finish the drag harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - harness.run_steps(3); + harness.run_steps(1); } /// Press and release the primary button at `at` From 695a3eed910226ef6e815df4a47c8de5e6de2667 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 08:22:27 +0000 Subject: [PATCH 35/73] Shift+click paints straight lines in the 2D view The 2D view keeps the end of the last finished stroke in texture coordinates, with its texture set, so a line drawn after zooming or panning joins the same texels, and previews the line while Shift is held, as the 3D view does. A cancelled stroke (Escape) leaves the line start where it was. Session::continue_stroke_uv stamps a long segment in batches of 4096 up to 1 << 17 stamps instead of stopping at 4096, keeps its carry within one step, and seeds stamps from the stroke's running count (UvStrokeState) so noise alphas don't repeat every pointer sample. The line preview is clipped to the view, keeping its dash phase. Refs #306 --- crates/engine/src/lib.rs | 1 + crates/engine/src/painting.rs | 83 +++++++----- crates/engine/src/session.rs | 4 +- crates/engine/src/uv_stroke_state.rs | 14 ++ crates/engine/tests/uv_strokes.rs | 77 +++++++++++ crates/ui-egui/src/lib.rs | 25 +++- crates/ui-egui/src/viewport.rs | 171 ++++++++++++++++++----- crates/ui-egui/tests/shift_lines_2d.rs | 180 +++++++++++++++++++++++++ 8 files changed, 482 insertions(+), 73 deletions(-) create mode 100644 crates/engine/src/uv_stroke_state.rs create mode 100644 crates/engine/tests/uv_strokes.rs create mode 100644 crates/ui-egui/tests/shift_lines_2d.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..a6c444e0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -45,6 +45,7 @@ pub mod smart_masks; pub mod template_cmds; pub mod text_cmds; pub mod tool_cmds; +mod uv_stroke_state; pub mod uv_tile_cmds; pub mod view_cmds; diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 6f2a74ff..c9c19085 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -12,8 +12,18 @@ use texturecraft_paint::{ }; use crate::session::{ActiveStroke, CloneFrom, FillMode, Session, StackTarget, Tool}; +use crate::uv_stroke_state::UvStrokeState; use crate::{EngineError, Result}; +/// Shortest distance between 2D view stamps, so a stamp with no radius (a pen at zero pressure) can't stall a stroke. +const MIN_UV_STAMP_STEP: f32 = 1e-5; + +/// 2D view stamps rasterized together, bounding the memory of one batch. +const UV_STAMP_BATCH: usize = 4096; + +/// Most stamps one 2D view sample adds: a line across the texture at the finest brush (about 71k) fits, a hostile coordinate stays bounded. +const MAX_UV_STAMPS_PER_SAMPLE: usize = 1 << 17; + impl Session { /// Camera visibility for a stroke at `viewport` (cached until the camera, size or mesh change). fn eye_depth(&mut self, viewport: Vec2) -> std::sync::Arc { @@ -234,7 +244,7 @@ impl Session { stroke, canvas, depth, - uv: uv_mode.then_some((None, 0.0)), + uv: uv_mode.then(UvStrokeState::default), camera: self.camera, viewport, values, @@ -314,40 +324,45 @@ impl Session { /// Add a 2D view sample (texture coordinates). Brush size is relative to the UV square. pub fn continue_stroke_uv(&mut self, uv: Vec2, pressure: f32) { - let Some(st) = self.stroke.as_mut() else { return }; - let Some((last, carry)) = st.uv.as_mut() else { return }; - let Some(cache) = self.caches.get_mut(st.ts) else { return }; - let b = &st.stroke.settings; - let p = pressure.clamp(0.0, 1.0); - let radius = b.size * 2.0 * if p < 1.0 { b.min_size + (1.0 - b.min_size) * p } else { 1.0 }; - let step = (b.spacing * 2.0 * radius).max(1e-5); - let mut points = Vec::new(); - match *last { - None => points.push(uv), - Some(prev) => { - let seg = uv - prev; - let len = seg.length(); - let mut t = step - *carry; - while t <= len && points.len() < 4096 { - points.push(prev + seg * (t / len.max(1e-9))); - t += step; - } - *carry = len - (t - step); - } - } - // Follow path: turn the stamp with the stroke direction (y up on screen, v grows down). - let angle = match *last { - Some(prev) if b.follow_path && uv != prev => b.angle + (prev.y - uv.y).atan2(uv.x - prev.x).to_degrees() - 90.0, - _ => b.angle, + let Some(active) = self.stroke.as_mut() else { return }; + let Some(progress) = active.uv.as_mut() else { return }; + let Some(cache) = self.caches.get_mut(active.ts) else { return }; + let settings = &active.stroke.settings; + let pressure = pressure.clamp(0.0, 1.0); + let size_scale = if pressure < 1.0 { settings.min_size + (1.0 - settings.min_size) * pressure } else { 1.0 }; + let radius = settings.size * 2.0 * size_scale; + let step = (settings.spacing * 2.0 * radius).max(MIN_UV_STAMP_STEP); + + // Follow path: turn the stamp with the stroke direction (y up on screen, v grows down) + let angle = match progress.last { + Some(previous) if settings.follow_path && uv != previous => settings.angle + (previous.y - uv.y).atan2(uv.x - previous.x).to_degrees() - 90.0, + _ => settings.angle, }; - *last = Some(uv); - let n0 = st.stroke.stamps.len() as u32; - let stamps: Vec = points - .iter() - .enumerate() - .map(|(i, c)| texturecraft_paint::UvStamp { center: *c, radius, angle, flow: b.flow, hardness: b.hardness, seed: n0 + i as u32 }) - .collect(); - texturecraft_paint::rasterize_uv(&mut st.canvas, &cache.gbuf, Self::shape(&self.images, b), &stamps); + + // The first sample is one stamp; a later one stamps every `step` along the segment from the previous + let (start, segment, mut distance) = match progress.last.replace(uv) { + None => (uv, Vec2::ZERO, 0.0), + Some(previous) => (previous, uv - previous, step - progress.carry), + }; + let length = segment.length(); + let shape = Self::shape(&self.images, settings); + let mut stamped = 0; + while distance <= length && stamped < MAX_UV_STAMPS_PER_SAMPLE { + let batch_size = UV_STAMP_BATCH.min(MAX_UV_STAMPS_PER_SAMPLE - stamped); + let mut batch = Vec::new(); + while distance <= length && batch.len() < batch_size { + let center = start + segment * (distance / length.max(f32::MIN_POSITIVE)); + let seed = progress.stamps.wrapping_add((stamped + batch.len()) as u32); + batch.push(texturecraft_paint::UvStamp { center, radius, angle, flow: settings.flow, hardness: settings.hardness, seed }); + distance += step; + } + stamped += batch.len(); + texturecraft_paint::rasterize_uv(&mut active.canvas, &cache.gbuf, shape, &batch); + } + + // At most one step, so a segment cut off at the stamp limit can't push the next one's stamps backwards + progress.carry = (length - (distance - step)).min(step); + progress.stamps = progress.stamps.wrapping_add(stamped as u32); self.stroke_painted(); } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 36263560..137affdc 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -291,8 +291,8 @@ pub(crate) struct ActiveStroke { pub canvas: StrokeCanvas, /// Camera visibility for 3D strokes (None for strokes in the 2D view). pub depth: Option>, - /// 2D view strokes: last UV point and the distance carried to the next stamp. - pub uv: Option<(Option, f32)>, + /// 2D view strokes: where the stroke is between samples. + pub uv: Option, pub camera: OrbitCamera, pub viewport: Vec2, pub values: BTreeMap, diff --git a/crates/engine/src/uv_stroke_state.rs b/crates/engine/src/uv_stroke_state.rs new file mode 100644 index 00000000..5ce5ae2f --- /dev/null +++ b/crates/engine/src/uv_stroke_state.rs @@ -0,0 +1,14 @@ +//! Where a stroke in the 2D view is between pointer samples. + +use texturecraft_geom::glam::Vec2; + +/// A 2D view stroke's progress: its last point, the distance carried to the next stamp and the stamps so far. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct UvStrokeState { + /// The last sample's texture coordinates (None before the first sample). + pub last: Option, + /// Distance from the last stamp to the last sample, at most one stamp step. + pub carry: f32, + /// Stamps so far: the next stamp's seed, so noise alphas don't repeat from sample to sample. + pub stamps: u32, +} diff --git a/crates/engine/tests/uv_strokes.rs b/crates/engine/tests/uv_strokes.rs new file mode 100644 index 00000000..b17fb0bf --- /dev/null +++ b/crates/engine/tests/uv_strokes.rs @@ -0,0 +1,77 @@ +//! Stamping along 2D view strokes: long segments, the carry between samples and per-stamp seeds + +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// Texture size: 1e-4 UV is 0.0256 texels +const RESOLUTION: u32 = 256; + +/// A sphere project painting red with `brush` settings (the UI's 0–100 scales) +fn red_brush_session(brush: serde_json::Value) -> Session { + let mut session = Session::new_project("UV strokes", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + execute(&mut session, "tool.paint", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &brush).unwrap(); + session +} + +/// The composite base color at texel (`x`, `y`) +fn color_at(session: &Session, x: u32, y: u32) -> [f32; 3] { + session.caches[0].composite.value(Channel::BaseColor, x, y) +} + +/// Whether the composite base color at (`u`, `v`) is the painted red +fn red_at(session: &Session, u: f32, v: f32) -> bool { + let color = color_at(session, (u * RESOLUTION as f32) as u32, (v * RESOLUTION as f32) as u32); + color[0] > 0.85 && color[1] < 0.15 +} + +#[test] +fn a_segment_longer_than_one_stamp_batch_paints_to_its_end() { + // 1e-4 UV between stamps: 0.9 UV is 9000 stamps, past the 4096 of one batch + let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.05, 0.5], [0.95, 0.5]]})).unwrap(); + + for u in [0.1, 0.5, 0.9] { + assert!(red_at(&session, u, 0.5), "painted at u = {u}"); + } +} + +#[test] +fn a_segment_cut_at_the_stamp_limit_does_not_stamp_the_next_one_backwards() { + // 1e-4 UV between stamps: the 20.5 UV first segment needs 205k stamps and is cut off the texture, near u = -6.9 + let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[-20.0, 0.5], [0.5, 0.5], [0.6, 0.5]]})).unwrap(); + + assert!(red_at(&session, 0.55, 0.5), "the last segment is painted"); + assert!(!red_at(&session, 0.3, 0.5), "nothing is stamped behind the last segment's start"); +} + +#[test] +fn each_sample_of_a_stroke_stamps_new_noise() { + // A 32 texel radius at full spacing: one stamp per sample, each centred on a texel at u = 0.25 and 0.5 + let mut session = red_brush_session(json!({"size": 25.0, "spacing": 100.0, "alpha": "cloud"})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.25, 0.5], [0.5, 0.5]]})).unwrap(); + + let patch = |centre_x: u32| -> Vec<[f32; 3]> { + (centre_x - 16..centre_x + 16).flat_map(|x| (112..144).map(move |y| (x, y))).map(|(x, y)| color_at(&session, x, y)).collect() + }; + let first_stamp = patch(64); + assert!(first_stamp.iter().any(|color| color[0] > 0.5 && color[1] < 0.5), "the first stamp painted"); + assert_ne!(first_stamp, patch(128), "the second sample's stamp has its own noise"); +} + +#[test] +fn a_hostile_segment_stays_bounded() { + // The finest brush the settings allow: 2e-5 UV between stamps + let mut session = red_brush_session(json!({"size": 0.2, "spacing": 1.0})); + + let result = execute(&mut session, "tool.strokeUv", &json!({"points": [[0.0, 0.0], [1e9, 1e9]]})); + + assert!(result.is_ok(), "{result:?}"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..15d22ac5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -110,6 +110,8 @@ pub struct TextureCraftApp { pub profiler: profile::Profiler, /// Where the last 3D stroke ended (viewport pixels), for Shift+click straight lines. pub last_paint_point: Option, + /// Where the last finished 2D view stroke ended: its texture set and texture coordinates (so zoom and pan keep it), for Shift+click straight lines. + pub last_paint_uv: Option<(usize, texturecraft_engine::geom::glam::Vec2)>, /// The decal layer the next click in the 3D view places. pub placing_decal: Option, /// The Properties popup a right click in a view opens. @@ -133,19 +135,23 @@ pub struct TextureCraftApp { } impl TextureCraftApp { + /// The app around `session`, with the saved UI state (or defaults in the OS language) and the GPU viewport. pub fn new(cc: &eframe::CreationContext<'_>, session: Session) -> TextureCraftApp { theme::install(&cc.egui_ctx); - // Bakes cast their rays on a GPU device of their own (created on the first bake). + + // Bakes cast their rays on a GPU device of their own (created on the first bake) #[cfg(not(target_arch = "wasm32"))] texturecraft_engine::bake::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); - let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx)); - // The first run speaks the OS (or browser) language. - let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_else(|| { + let gpu = cc.wgpu_render_state.as_ref().map(|render_state| gpu::init(render_state, &cc.egui_ctx)); + + // The first run speaks the OS (or browser) language + let ui = cc.storage.and_then(|storage| eframe::get_value::(storage, "ui")).unwrap_or_else(|| { let mut ui = UiState::default(); ui.prefs.language = i18n::os_language().into(); ui }); let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0; + let mut app = TextureCraftApp { camera_glide: None, session, @@ -166,6 +172,7 @@ impl TextureCraftApp { brushes: None, render: render_mode::RenderView::default(), last_paint_point: None, + last_paint_uv: None, placing_decal: None, properties_popup: None, render_state: cc.wgpu_render_state.clone(), @@ -181,17 +188,21 @@ impl TextureCraftApp { app.ui.windows.new_project = false; i18n::set_language(&app.ui.prefs.language); export_templates::load_library(&mut app, cc.storage); + #[cfg(not(target_arch = "wasm32"))] { - // The first window of the process fixes it; a new folder applies on restart. + // The first window of the process fixes it; a new folder applies on restart let _ = DATA_FOLDER.set(data_folder(&app.ui.prefs.data_folder)); - // An export folder still at the default follows the data folder. + + // An export folder still at the default follows the data folder if app.ui.export.dir == data_folder("").join("export").display().to_string() { app.ui.export.dir = user_dir("export").display().to_string(); } + let skipped = app.session.load_templates(user_dir("templates")); - app.session.log.extend(skipped.into_iter().map(|w| format!("Project template skipped: {w}"))); + app.session.log.extend(skipped.into_iter().map(|warning| format!("Project template skipped: {warning}"))); } + app } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..cb1c9bc1 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -165,6 +165,18 @@ const UV_VIEW_MAX_ZOOM: f32 = 40.0; /// UV zoom change per point of mouse wheel, as a fraction of the zoom const UV_WHEEL_ZOOM_PER_POINT: f32 = 0.002; +/// Dash length of the straight-line preview, in points +const RUBBER_BAND_DASH: f32 = 6.0; + +/// Gap between the straight-line preview's dashes, in points +const RUBBER_BAND_GAP: f32 = 4.0; + +/// Opacity of the UV tile outlines in the 2D view +const UV_TILE_OUTLINE_ALPHA: u8 = 40; + +/// Smallest skew brush circle in the 2D view, in points, so a tiny brush stays visible +const BAKE_PAINT_CURSOR_MIN_RADIUS: f32 = 2.0; + /// The 2D view's width when the split divider is at `divider_x` fn uv_view_width(full: Rect, divider_x: f32) -> f32 { (full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0) @@ -996,11 +1008,43 @@ fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Respons } } -/// Dashed preview of a straight segment. +/// Dashed preview of a straight segment, clipped to `rect` so an end far off screen adds no dashes. fn rubber_band(ui: &Ui, rect: Rect, from: Pos2, to: Pos2) { - let p = ui.painter_at(rect); - p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(2.5, Color32::from_black_alpha(120)), 6.0, 4.0)); - p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(1.0, Color32::from_white_alpha(200)), 6.0, 4.0)); + let Some(visible) = visible_dashes(rect, from, to) else { return }; + let painter = ui.painter_at(rect); + for stroke in [Stroke::new(2.5, Color32::from_black_alpha(120)), Stroke::new(1.0, Color32::from_white_alpha(200))] { + painter.add(egui::Shape::dashed_line(&visible, stroke, RUBBER_BAND_DASH, RUBBER_BAND_GAP)); + } +} + +/// The part of `from`→`to` inside `rect`, its start moved back to a whole dash period so the dashes keep their place. +fn visible_dashes(rect: Rect, from: Pos2, to: Pos2) -> Option<[Pos2; 2]> { + let direction = to - from; + let length = direction.length(); + if length == 0.0 { + return rect.contains(from).then_some([from, to]); + } + + // Clip the segment's parameter range against each axis's slab + let (mut enter, mut exit) = (0.0_f32, 1.0_f32); + for (delta, origin, low, high) in [(direction.x, from.x, rect.left(), rect.right()), (direction.y, from.y, rect.top(), rect.bottom())] { + if delta == 0.0 { + if origin < low || origin > high { + return None; + } + continue; + } + let (at_low, at_high) = ((low - origin) / delta, (high - origin) / delta); + enter = enter.max(at_low.min(at_high)); + exit = exit.min(at_low.max(at_high)); + } + if enter > exit { + return None; + } + + let period = RUBBER_BAND_DASH + RUBBER_BAND_GAP; + let start = (enter * length / period).floor() * period / length; + Some([from + direction * start, from + direction * exit]) } /// V held with the Clone tool in painting mode: clicks set the clone source. @@ -1148,11 +1192,12 @@ fn pen_pressure(ui: &Ui) -> f32 { } } +/// The 2D (UV) view: navigation, painting in texture coordinates and the overlays drawn over the texture. fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { let tokens = Tokens::get(ui.ctx()); let response = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); let size = rect.size(); - let alt = ui.input(|input| input.modifiers.alt); + let (alt, shift) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift)); let adjusting = brush_drag(app, ui, &response); // Pan with a middle drag or Alt+left drag, zoom with the wheel about the cursor @@ -1216,29 +1261,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if painting && path_tool { path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); } else if painting { - let pressure = pen_pressure(ui); - if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { - if let Some(pointer) = response.interact_pointer_pos() - && let Err(error) = app.session.begin_stroke_uv(to_uv(pointer), pressure) - { - app.toast(error.to_string(), true); - } - if response.clicked_by(PointerButton::Primary) - && let Err(error) = app.session.end_stroke() - { - app.toast(error.to_string(), true); - } - } else if response.dragged_by(PointerButton::Primary) - && app.session.stroke_active() - && let Some(pointer) = response.interact_pointer_pos() - { - app.session.continue_stroke_uv(to_uv(pointer), pressure); - } - if response.drag_stopped_by(PointerButton::Primary) - && let Err(error) = app.session.end_stroke() - { - app.toast(error.to_string(), true); - } + paint_2d_input(app, ui, &response, shift, &to_uv); } if response.double_clicked() && !(painting && path_tool) { app.ui.uv_zoom = 1.0; @@ -1259,7 +1282,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // The UV tile outlines (numbered for UDIM sets) and the path being edited let painter = ui.painter_at(rect); let set = app.session.doc.project.texture_sets.get(ts); - let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(40)), egui::StrokeKind::Outside); + let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(UV_TILE_OUTLINE_ALPHA)), egui::StrokeKind::Outside); match set.and_then(|texture_set| Some((texture_set, texture_set.tile_grid()?))) { Some((texture_set, grid)) => { for (udim, (block_x, block_y)) in texture_set.uv_tiles.iter().filter_map(|udim| Some((*udim, grid.block(*udim)?))) { @@ -1285,10 +1308,22 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin path_overlay(app, ui, rect, &response, true, show); } + // Shift: preview the straight line Shift+click paints from the last stroke + if painting + && shift + && !path_tool + && brush_tool(app.session.tool.tool) + && let Some((last_set, from)) = app.last_paint_uv + && last_set == ts + && let Some(hover) = response.hover_pos() + { + rubber_band(ui, rect, to_screen(from.x, from.y), hover); + } + if app.ui.mode == crate::state::Mode::Baking { bake_paint_overlay(app, ui, &painter, to_screen(0.0, 1.0), to_screen(1.0, 0.0)); if bake_paint_on && let Some(hover) = response.hover_pos() { - let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(2.0); + let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(BAKE_PAINT_CURSOR_MIN_RADIUS); painter.circle_stroke(hover, radius, Stroke::new(1.0, Color32::from_white_alpha(200))); } } @@ -1300,6 +1335,51 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tokens.viewport_text); } +/// Paint in the 2D view: a press starts a stroke, a drag continues it, Shift+click draws a line from the last stroke. +fn paint_2d_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, shift: bool, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { + let pressure = pen_pressure(ui); + let set = app.session.ts(); + // Where the stroke under way is; it becomes the line start only when the stroke finishes + let stroke_end = ui.scope_id().with("paint_2d_stroke_end"); + + if resp.drag_started_by(PointerButton::Primary) || resp.clicked_by(PointerButton::Primary) { + // A line starts only from a point on the same texture set + let line_start = match app.last_paint_uv { + Some((last_set, last_uv)) if shift && last_set == set => Some(last_uv), + _ => None, + }; + if let Some(pointer) = resp.interact_pointer_pos() { + let uv = to_uv(pointer); + match app.session.begin_stroke_uv(line_start.unwrap_or(uv), pressure) { + Ok(()) => { + if line_start.is_some() { + app.session.continue_stroke_uv(uv, pressure); + } + ui.data_mut(|data| data.insert_temp(stroke_end, (set, uv))); + } + Err(error) => app.toast(error.to_string(), true), + } + } + } else if resp.dragged_by(PointerButton::Primary) + && app.session.stroke_active() + && let Some(pointer) = resp.interact_pointer_pos() + { + let uv = to_uv(pointer); + app.session.continue_stroke_uv(uv, pressure); + ui.data_mut(|data| data.insert_temp(stroke_end, (set, uv))); + } + + // Escape cancels the stroke and ends the drag without a primary release, so a cancelled stroke never gets here + if resp.clicked_by(PointerButton::Primary) || resp.drag_stopped_by(PointerButton::Primary) { + let finishing = app.session.stroke_active(); + match app.session.end_stroke() { + Ok(()) if finishing => app.last_paint_uv = ui.data(|data| data.get_temp(stroke_end)), + Ok(()) => {} + Err(error) => app.toast(error.to_string(), true), + } + } +} + /// Paint the skew map under the pointer in the 2D view (a click is one dab, a drag a stroke). fn bake_paint_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { let last = ui.scope_id().with(("bake_paint_last", app.session.ts(), app.ui.bake_paint_brush.target as u8)); @@ -1351,3 +1431,34 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t }; painter.image(tex.id(), Rect::from_two_pos(top_left, bottom_right), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } + +#[cfg(test)] +mod tests { + use super::*; + + const VIEW: Rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0)); + const DASH_PERIOD: f32 = RUBBER_BAND_DASH + RUBBER_BAND_GAP; + + #[test] + fn a_far_start_is_clipped_to_the_view_on_a_whole_dash_period() { + let far_start = pos2(-10_003.0, 50.0); + + let [start, end] = visible_dashes(VIEW, far_start, pos2(50.0, 50.0)).unwrap(); + + assert!(start.x <= VIEW.left() && start.x > VIEW.left() - DASH_PERIOD, "starts at the view's edge: {start:?}"); + let periods = (start.x - far_start.x) / DASH_PERIOD; + assert!((periods - periods.round()).abs() < 1e-3, "a whole number of dash periods from the real start: {periods}"); + assert_eq!(end, pos2(50.0, 50.0)); + } + + #[test] + fn a_segment_inside_the_view_is_kept_whole() { + assert_eq!(visible_dashes(VIEW, pos2(10.0, 20.0), pos2(90.0, 80.0)), Some([pos2(10.0, 20.0), pos2(90.0, 80.0)])); + } + + #[test] + fn a_segment_outside_the_view_draws_nothing() { + assert_eq!(visible_dashes(VIEW, pos2(-50.0, -10.0), pos2(150.0, -10.0)), None); + assert_eq!(visible_dashes(VIEW, pos2(-50.0, 120.0), pos2(120.0, 300.0)), None); + } +} diff --git a/crates/ui-egui/tests/shift_lines_2d.rs b/crates/ui-egui/tests/shift_lines_2d.rs new file mode 100644 index 00000000..5b87f409 --- /dev/null +++ b/crates/ui-egui/tests/shift_lines_2d.rs @@ -0,0 +1,180 @@ +//! Shift+click in the 2D view paints a straight line from where the last stroke ended, as in the 3D view + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; + +/// The first click, on the sample's texture in the 2D view +const FIRST_CLICK: Pos2 = pos2(700.0, 420.0); + +/// The Shift+click, on the texture of both of the sample's texture sets +const SECOND_CLICK: Pos2 = pos2(900.0, 520.0); + +/// Start of a drag cancelled with Escape, well away from the line between the two clicks +const CANCELLED_DRAG_FROM: Pos2 = pos2(760.0, 700.0); + +/// End of the cancelled drag +const CANCELLED_DRAG_TO: Pos2 = pos2(820.0, 700.0); + +/// Alpha a texel needs to count as painted +const PAINTED_ALPHA: f32 = 0.05; + +/// How far beside the line the unpainted check looks, in brush radii +const BESIDE_LINE_IN_RADII: f32 = 3.0; + +/// The sample project with only the 2D view, at 1600 x 960 +fn uv_view_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(4); + harness +} + +/// A primary click at `pos`, with Shift held when `shift` is set +fn click(harness: &mut Harness<'_, TextureCraftApp>, pos: Pos2, shift: bool) { + let modifiers = if shift { Modifiers::SHIFT } else { Modifiers::NONE }; + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(pos); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(1); +} + +/// Press at `from`, drag to `to`, press Escape and release: the stroke is cancelled +fn cancelled_drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.hover_at(to); + harness.run_steps(2); + harness.key_press(egui::Key::Escape); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(!harness.state().session.stroke_active(), "Escape cancelled the stroke"); +} + +/// The selected layer's base color alpha, row by row, with the texture width +fn alpha(harness: &Harness<'_, TextureCraftApp>) -> (Vec, u32) { + let session = &harness.state().session; + let (width, height) = session.doc.project.texture_sets[session.ts()].size(); + let layer = session.selected_layer().expect("a selected layer"); + let Some(image) = session.doc.pixels.layer(layer, Channel::BaseColor) else { return (vec![0.0; (width * height) as usize], width) }; + let texels = (0..height).flat_map(|y| (0..width).map(move |x| (x, y))); + (texels.map(|(x, y)| image.get(x, y)[3] as f32 / 65535.0).collect(), width) +} + +/// Alpha added between two snapshots +fn added(before: &[f32], after: &[f32]) -> Vec { + after.iter().zip(before).map(|(after, before)| (after - before).max(0.0)).collect() +} + +/// The alpha-weighted centre of `paint`, in texels +fn centre(paint: &[f32], width: u32) -> Vec2 { + let (sum, total) = paint.iter().enumerate().fold((Vec2::ZERO, 0.0), |(sum, total), (index, value)| { + let texel = Vec2::new((index as u32 % width) as f32, (index as u32 / width) as f32); + (sum + texel * *value, total + value) + }); + assert!(total > 0.0, "something was painted"); + sum / total +} + +/// Whether `paint` holds visible alpha at `texel` +fn painted_at(paint: &[f32], width: u32, texel: Vec2) -> bool { + let index = texel.y.round() as usize * width as usize + texel.x.round() as usize; + paint[index] > PAINTED_ALPHA +} + +/// The brush radius in texels: a 2D view stamp's radius is twice the brush size in UV units +fn brush_radius_in_texels(harness: &Harness<'_, TextureCraftApp>, width: u32) -> f32 { + harness.state().session.tool.brush.size * 2.0 * width as f32 +} + +/// Click, run `between` (zoom or pan), Shift+click; assert one straight stroke joins both dabs +fn assert_shift_click_draws_a_line(between: impl FnOnce(&mut Harness<'_, TextureCraftApp>)) { + let mut harness = uv_view_app(); + let (blank, width) = alpha(&harness); + click(&mut harness, FIRST_CLICK, false); + let (first_dab, _) = alpha(&harness); + let start = centre(&added(&blank, &first_dab), width); + + between(&mut harness); + harness.run_steps(2); + let steps_before = harness.state().session.history_labels().len(); + click(&mut harness, SECOND_CLICK, true); + assert_eq!(harness.state().session.history_labels().len(), steps_before + 1, "the line is one undo step"); + let (with_line, _) = alpha(&harness); + let line = added(&first_dab, &with_line); + + // A plain click at the same point finds where the line should end + harness.state_mut().session.undo().unwrap(); + click(&mut harness, SECOND_CLICK, false); + let (with_dab, _) = alpha(&harness); + let end = centre(&added(&first_dab, &with_dab), width); + + let middle = (start + end) * 0.5; + let across = (end - start).perp().normalize() * brush_radius_in_texels(&harness, width) * BESIDE_LINE_IN_RADII; + assert!(painted_at(&line, width, middle), "the line passes halfway between {start} and {end}"); + assert!(!painted_at(&line, width, middle + across), "nothing is painted beside the line"); +} + +#[test] +fn shift_click_paints_a_straight_line_from_the_last_stroke() { + assert_shift_click_draws_a_line(|_| {}); +} + +#[test] +fn the_line_joins_the_same_texture_points_after_zoom_and_pan() { + assert_shift_click_draws_a_line(|harness| { + let ui_state = &mut harness.state_mut().ui; + ui_state.uv_zoom *= 1.5; + ui_state.uv_pan = [0.2, -0.1]; + }); +} + +/// Shift+click at the second point; assert it painted the same dot a plain click there paints +fn assert_shift_click_paints_only_a_dot(harness: &mut Harness<'_, TextureCraftApp>) { + let (before, _) = alpha(harness); + click(harness, SECOND_CLICK, true); + let (after_shift_click, _) = alpha(harness); + let shift_click_alpha: f32 = added(&before, &after_shift_click).iter().sum(); + + harness.state_mut().session.undo().unwrap(); + click(harness, SECOND_CLICK, false); + let (after_click, _) = alpha(harness); + let click_alpha: f32 = added(&before, &after_click).iter().sum(); + + assert!(click_alpha > 1.0, "the plain click painted: {click_alpha}"); + assert!((shift_click_alpha - click_alpha).abs() < click_alpha * 0.01, "Shift+click paints only a dot: {shift_click_alpha} vs {click_alpha}"); +} + +#[test] +fn shift_click_without_a_previous_stroke_paints_a_dot() { + assert_shift_click_paints_only_a_dot(&mut uv_view_app()); +} + +#[test] +fn a_line_does_not_start_from_a_point_on_another_texture_set() { + let mut harness = uv_view_app(); + click(&mut harness, FIRST_CLICK, false); + + harness.state_mut().run("textureSet.select", json!({"ts": 1})); + harness.run_steps(2); + + assert_shift_click_paints_only_a_dot(&mut harness); +} + +#[test] +fn a_stroke_cancelled_with_escape_leaves_the_line_start_where_it_was() { + assert_shift_click_draws_a_line(|harness| cancelled_drag(harness, CANCELLED_DRAG_FROM, CANCELLED_DRAG_TO)); +} From cfe837b86cb83b60c4224aa04f1fb8cf1d22b4cf Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 08:22:20 +0000 Subject: [PATCH 36/73] Import baked maps when creating a project New project > Advanced settings gets the project's normal map format and Import baked maps: Add lists image files, and Create imports them with the new textureSet.meshMap.import command, which sets each file as the mesh map of the texture set and slot its name names (Body_ambient_occlusion.png, Body_normal.1001.png) in one undo step and reports the files it left out. --- crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 2 + crates/engine/src/meshmap_cmds.rs | 43 ++--- crates/engine/src/meshmap_file_name.rs | 153 +++++++++++++++++ crates/engine/src/meshmap_import_cmds.rs | 79 +++++++++ crates/engine/src/resource_cmds.rs | 35 ++-- crates/engine/tests/meshmap_import.rs | 136 +++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 6 + crates/ui-egui/src/i18n/de.rs | 6 + crates/ui-egui/src/i18n/es.rs | 6 + crates/ui-egui/src/i18n/fr.rs | 6 + crates/ui-egui/src/i18n/it.rs | 6 + crates/ui-egui/src/i18n/ja.rs | 6 + crates/ui-egui/src/i18n/ko.rs | 6 + crates/ui-egui/src/i18n/pt_br.rs | 6 + crates/ui-egui/src/i18n/zh_hans.rs | 6 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/new_project_advanced.rs | 155 ++++++++++++++++++ crates/ui-egui/src/state.rs | 10 +- crates/ui-egui/src/windows.rs | 7 +- .../ui-egui/tests/new_project_baked_maps.rs | 80 +++++++++ docs/control-protocol.md | 2 +- 22 files changed, 725 insertions(+), 33 deletions(-) create mode 100644 crates/engine/src/meshmap_file_name.rs create mode 100644 crates/engine/src/meshmap_import_cmds.rs create mode 100644 crates/engine/tests/meshmap_import.rs create mode 100644 crates/ui-egui/src/new_project_advanced.rs create mode 100644 crates/ui-egui/tests/new_project_baked_maps.rs diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 9f0d126b..922c380b 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -65,6 +65,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::quick_mask::specs()); v.extend(crate::set_cmds::specs()); v.extend(crate::meshmap_cmds::specs()); + v.extend(crate::meshmap_import_cmds::specs()); v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..da0ab3ae 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -29,6 +29,8 @@ pub mod material_lib; pub mod materials; pub mod materialx_cmds; pub mod meshmap_cmds; +mod meshmap_file_name; +pub mod meshmap_import_cmds; pub mod painting; pub mod path_tool; // Mesh reimport reads files: native only. diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 0fbe1f5b..932ba137 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -38,11 +38,17 @@ fn set(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, CMD)?; let map = map_param(p, CMD)?; let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?; - let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?; + let resolution = s.edit("Use image as mesh map", |s| use_image(s, CMD, ts, map, name))?; + Ok(json!({ "map": map.id(), "resolution": resolution })) +} + +/// Use image resource `name` as mesh map `map` of set `ts` inside the caller's edit; returns the map width +pub(crate) fn use_image(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, name: &str) -> Result { + let img = s.images.get(name).cloned().ok_or_else(|| bad(cmd, format!("no image resource `{name}`")))?; let set = s.doc.project.texture_set(ts)?.clone(); - let tiles = set.tile_grid().map(|grid| tile_images(&s.images, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?; - // Every mesh map of a set shares one size: the other maps', or what a bake would make (a - // block of the bake resolution per tile of the atlas). + let tiles = set.tile_grid().map(|grid| tile_images(&s.images, cmd, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?; + + // Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile) let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows)); let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) { Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))), @@ -52,37 +58,34 @@ fn set(s: &mut Session, p: &Value) -> Result { } }; if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) { - return Err(bad(CMD, format!("mesh map size {res} × {height} is too large or empty"))); + return Err(bad(cmd, format!("mesh map size {res} × {height} is too large or empty"))); } + let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; let data = match &tiles { None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)), - // An atlas texel reads the image of the tile its mesh UV falls in. + // An atlas texel reads the image of the tile its mesh UV falls in Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| { let uv = grid.from_atlas([u, v]); udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) }), }; - s.edit("Use image as mesh map", |s| { - let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = res; - entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); - Ok(()) - })?; - Ok(json!({ "map": map.id(), "resolution": res })) + + let entry = s.doc.baked.entry(ts).or_default(); + entry.resolution = res; + entry.maps.insert(map, Arc::new(data)); + s.doc.project.texture_set_mut(ts)?.baked.insert(map); + Ok(res) } -/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for -/// each tile's. -fn tile_images(images: &ImageStore, name: &str, tiles: &[u32]) -> Result>> { - const CMD: &str = "textureSet.meshMap.set"; - let at = udim_in(name).ok_or_else(|| bad(CMD, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; +/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for each tile's +fn tile_images(images: &ImageStore, cmd: &str, name: &str, tiles: &[u32]) -> Result>> { + let at = udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; tiles .iter() .map(|&t| { let tile_name = format!("{}{t}{}", name.get(..at).unwrap_or_default(), name.get(at + 4..).unwrap_or_default()); - images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(CMD, format!("no image `{tile_name}` for UV tile {t}"))) + images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {t}"))) }) .collect() } diff --git a/crates/engine/src/meshmap_file_name.rs b/crates/engine/src/meshmap_file_name.rs new file mode 100644 index 00000000..cfc4f125 --- /dev/null +++ b/crates/engine/src/meshmap_file_name.rs @@ -0,0 +1,153 @@ +//! Which texture set and mesh map a baked map file is for, by file name (`Body_ao.1001.png` = Body's ambient occlusion) + +use std::path::Path; + +use texturecraft_core::{BakedMap, UDIM_RANGE}; + +/// Mesh maps named by two words anywhere in the file name; they win over the one-word names +const TWO_WORD_NAMES: [(&str, &[&str], BakedMap); 3] = [ + ("world", &["normal", "normals"], BakedMap::WorldNormal), + ("bent", &["normal", "normals"], BakedMap::BentNormal), + ("ambient", &["occlusion"], BakedMap::AmbientOcclusion), +]; + +const ONE_WORD_NAMES: [(&str, BakedMap); 20] = [ + ("worldnormal", BakedMap::WorldNormal), + ("worldnormals", BakedMap::WorldNormal), + ("bentnormal", BakedMap::BentNormal), + ("bentnormals", BakedMap::BentNormal), + ("ambientocclusion", BakedMap::AmbientOcclusion), + ("normal", BakedMap::Normal), + ("normals", BakedMap::Normal), + ("nrm", BakedMap::Normal), + ("occlusion", BakedMap::AmbientOcclusion), + ("ao", BakedMap::AmbientOcclusion), + ("curvature", BakedMap::Curvature), + ("curv", BakedMap::Curvature), + ("id", BakedMap::Id), + ("position", BakedMap::Position), + ("pos", BakedMap::Position), + ("thickness", BakedMap::Thickness), + ("height", BakedMap::Height), + ("displacement", BakedMap::Height), + ("opacity", BakedMap::Opacity), + ("alpha", BakedMap::Opacity), +]; + +fn is_separator(c: char) -> bool { + matches!(c, '_' | '-' | '.' | ' ') +} + +/// The file name without its folder and extension +fn stem(path: &str) -> &str { + Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or_default() +} + +/// The lowercase words of a file name, without UV tile numbers (`Body_AO.1001` → body, ao) +fn words(path: &str) -> Vec { + stem(path) + .split(is_separator) + .filter(|w| !w.is_empty() && !w.parse::().is_ok_and(|n| w.len() == 4 && UDIM_RANGE.contains(&n))) + .map(str::to_lowercase) + .collect() +} + +/// The mesh map a file holds, from the words of its name; the last recognised word wins +pub(crate) fn baked_map_from_file_name(path: &str) -> Option { + let words = words(path); + let has = |word: &str| words.iter().any(|w| w == word); + TWO_WORD_NAMES + .iter() + .find(|(first, seconds, _)| has(first) && seconds.iter().any(|s| has(s))) + .map(|(_, _, map)| *map) + .or_else(|| words.iter().rev().find_map(|w| ONE_WORD_NAMES.iter().find(|(name, _)| name == w).map(|(_, map)| *map))) +} + +/// The set a file is for: the longest set name its name starts with before a separator (any name with one set) +pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Option { + if set_names.len() == 1 { + return Some(0); + } + + let stem = stem(path).to_lowercase(); + set_names + .iter() + .enumerate() + .filter(|(_, name)| !name.is_empty()) + .filter(|(_, name)| stem.strip_prefix(&name.to_lowercase()).and_then(|rest| rest.chars().next()).is_some_and(is_separator)) + .max_by_key(|(_, name)| name.chars().count()) + .map(|(ts, _)| ts) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_word_names_its_map() { + let cases = [ + ("Body_normal.png", BakedMap::Normal), + ("Body_normals.png", BakedMap::Normal), + ("Body_nrm.png", BakedMap::Normal), + ("Body_world_normal.png", BakedMap::WorldNormal), + ("Body_normals_world.png", BakedMap::WorldNormal), + ("Body_WorldNormal.png", BakedMap::WorldNormal), + ("Body_bent_normals.png", BakedMap::BentNormal), + ("Body-ambient-occlusion.png", BakedMap::AmbientOcclusion), + ("Body_AmbientOcclusion.png", BakedMap::AmbientOcclusion), + ("Body_occlusion.png", BakedMap::AmbientOcclusion), + ("Body AO.png", BakedMap::AmbientOcclusion), + ("Body_curvature.png", BakedMap::Curvature), + ("Body_curv.png", BakedMap::Curvature), + ("Body_ID.png", BakedMap::Id), + ("Body_position.png", BakedMap::Position), + ("Body_pos.png", BakedMap::Position), + ("Body_thickness.png", BakedMap::Thickness), + ("Body_height.png", BakedMap::Height), + ("Body_displacement.png", BakedMap::Height), + ("Body_opacity.png", BakedMap::Opacity), + ("Body_alpha.png", BakedMap::Opacity), + ]; + for (file, map) in cases { + assert_eq!(baked_map_from_file_name(file), Some(map), "{file}"); + } + } + + #[test] + fn tile_numbers_and_folders_are_ignored() { + assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png"), Some(BakedMap::AmbientOcclusion)); + assert_eq!(baked_map_from_file_name("Body_normal_1002.tga"), Some(BakedMap::Normal)); + assert_eq!(texture_set_from_file_name("/bakes/Body_ao.1001.png", &["Head", "Body"]), Some(1)); + } + + #[test] + fn unknown_words_match_no_map() { + assert_eq!(baked_map_from_file_name("Body_diffuse.png"), None); + assert_eq!(baked_map_from_file_name("Body_1001.png"), None); + assert_eq!(baked_map_from_file_name("ambient.png"), None); + assert_eq!(baked_map_from_file_name(""), None); + } + + #[test] + fn the_longest_set_name_wins() { + let sets = ["Body", "Body_Upper", "Head"]; + assert_eq!(texture_set_from_file_name("Body_Upper_ao.png", &sets), Some(1)); + assert_eq!(texture_set_from_file_name("body_ao.png", &sets), Some(0)); + assert_eq!(texture_set_from_file_name("HEAD-normal.png", &sets), Some(2)); + } + + #[test] + fn a_set_name_must_end_at_a_separator() { + let sets = ["Body", "Head"]; + assert_eq!(texture_set_from_file_name("Bodywork_ao.png", &sets), None); + assert_eq!(texture_set_from_file_name("Arm_ao.png", &sets), None); + assert_eq!(texture_set_from_file_name("Body.png", &sets), None); + } + + #[test] + fn one_set_takes_every_file() { + assert_eq!(texture_set_from_file_name("ao.png", &["Body"]), Some(0)); + assert_eq!(texture_set_from_file_name("Head_ao.png", &["Body"]), Some(0)); + assert_eq!(texture_set_from_file_name("ao.png", &[]), None); + } +} diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs new file mode 100644 index 00000000..9770cf63 --- /dev/null +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -0,0 +1,79 @@ +//! Import mesh maps baked in another app: many files at once, each to the set and slot its file name names + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use texturecraft_core::BakedMap; + +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::meshmap_cmds::use_image; +use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name}; +use crate::resource_cmds::read_image_file; +use crate::{Result, Session, cmd}; + +const CMD: &str = "textureSet.meshMap.import"; + +/// Most files one import takes +const MAX_FILES: usize = 1024; + +pub fn specs() -> Vec { + vec![cmd!( + "textureSet.meshMap.import", + "Import baked maps", + [], + None, + "{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set: a UV-tiled set takes one file per tile (`Body_ao.1001.png`, `Body_ao.1002.png`). Files matching no set or map, and any file after the first for one slot, are left out and listed in `unmatched`. One undo step; desktop only", + always, + import + )] +} + +fn import(s: &mut Session, p: &Value) -> Result { + let files = p.get("files").and_then(Value::as_array).ok_or_else(|| bad(CMD, "`files` (a list of {path, map?}) is required"))?; + if files.len() > MAX_FILES { + return Err(bad(CMD, format!("at most {MAX_FILES} files at once"))); + } + + let set_names: Vec = s.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); + let set_names: Vec<&str> = set_names.iter().map(String::as_str).collect(); + let mut slots: BTreeMap<(usize, BakedMap), Vec<&str>> = BTreeMap::new(); + let mut unmatched = Vec::new(); + for file in files { + let path = strp(file, "path").ok_or_else(|| bad(CMD, "every file needs a `path`"))?; + let map = match strp(file, "map") { + Some(id) => Some(BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))?), + None => baked_map_from_file_name(path), + }; + match (texture_set_from_file_name(path, &set_names), map) { + (Some(ts), Some(map)) => slots.entry((ts, map)).or_default().push(path), + _ => unmatched.push(path), + } + } + + let result = s.edit("Import baked maps", |s| { + let mut assigned = Vec::new(); + for ((ts, map), paths) in &slots { + // A UV-tiled set reads every tile's file; any other set takes the first file for a slot + let files_used = if s.doc.project.texture_set(*ts)?.tile_grid().is_some() { paths.len() } else { 1 }; + let (taken, extra) = paths.split_at(files_used); + let mut image_name = None; + for path in taken { + let name = s.add_image_resource(path, read_image_file(CMD, path)?)?; + image_name.get_or_insert(name); + } + if let Some(name) = image_name { + use_image(s, CMD, *ts, *map, &name)?; + } + + assigned.extend(taken.iter().map(|path| json!({"path": path, "ts": ts, "map": map.id()}))); + unmatched.extend(extra); + } + Ok(assigned) + }); + // A failed edit leaves the document as it was; forget the images it decoded + if result.is_err() { + s.sync_images(); + } + + Ok(json!({ "assigned": result?, "unmatched": unmatched })) +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 87f6d50f..74682be8 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -38,9 +38,15 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { 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 { + self.edit("Import resource", |s| s.add_image_resource(file_name, bytes)) + } + + /// [`Session::import_resource_bytes`] without its own undo step, for imports inside a larger edit + pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec) -> Result { if bytes.len() > MAX_BYTES { return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); } + let image = texturecraft_formats::decode_image(&bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image"); let base = texturecraft_formats::sanitize_resource_name(leaf); @@ -50,11 +56,8 @@ impl Session { name = format!("{n}_{base}"); n += 1; } - let key = name.clone(); - self.edit("Import resource", |s| { - s.doc.resources.insert(key, Arc::new(bytes)); - Ok(()) - })?; + + self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); Ok(name) } @@ -98,15 +101,27 @@ fn list(s: &Session) -> Value { #[cfg(not(target_arch = "wasm32"))] fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; - let meta = std::fs::metadata(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?; - if meta.len() > MAX_BYTES as u64 { - return Err(bad("resource.import", format!("{path} is too large"))); - } - let bytes = std::fs::read(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?; + let bytes = read_image_file("resource.import", path)?; let name = s.import_resource_bytes(path, bytes)?; Ok(json!({ "name": name })) } +/// The bytes of the image file at `path`, refused above [`MAX_BYTES`] +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_image_file(cmd: &str, path: &str) -> Result> { + let meta = std::fs::metadata(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?; + if meta.len() > MAX_BYTES as u64 { + return Err(bad(cmd, format!("{path} is too large"))); + } + + std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}"))) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_image_file(cmd: &str, _: &str) -> Result> { + Err(bad(cmd, "file paths are not available in the browser")) +} + #[cfg(target_arch = "wasm32")] fn import(_: &mut Session, _: &Value) -> Result { Err(EngineError::Other("file paths are not available in the browser; use File > Import resources".into())) diff --git a/crates/engine/tests/meshmap_import.rs b/crates/engine/tests/meshmap_import.rs new file mode 100644 index 00000000..62a983d6 --- /dev/null +++ b/crates/engine/tests/meshmap_import.rs @@ -0,0 +1,136 @@ +//! Importing baked map files at once: each lands in the texture set and mesh map its name names + +use std::path::PathBuf; + +use serde_json::{Value, json}; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// The material ball: texture sets "Ball" and "Base" +fn session() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap() +} + +/// A folder of 4×4 gray PNGs named `files`, each with its own gray level +fn bake_folder(test: &str, files: &[&str]) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-meshmap-import-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for (index, file) in files.iter().enumerate() { + let gray = 20 + 20 * index as u8; + image::RgbaImage::from_pixel(4, 4, image::Rgba([gray, gray, gray, 255])).save(dir.join(file)).unwrap(); + } + dir +} + +fn import(s: &mut Session, dir: &PathBuf, files: &[(&str, Option<&str>)]) -> Value { + let files: Vec = files + .iter() + .map(|(file, map)| { + let path = dir.join(file).display().to_string(); + match map { + Some(map) => json!({"path": path, "map": map}), + None => json!({"path": path}), + } + }) + .collect(); + execute(s, "textureSet.meshMap.import", &json!({ "files": files })).unwrap() +} + +fn file_names(list: &Value) -> Vec { + list.as_array() + .unwrap() + .iter() + .map(|v| v.as_str().map_or_else(|| v["path"].as_str().unwrap(), |p| p)) + .map(|p| p.rsplit(['/', '\\']).next().unwrap().to_string()) + .collect() +} + +fn has_map(s: &Session, ts: usize, map: BakedMap) -> bool { + s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map) +} + +#[test] +fn files_go_to_the_set_and_map_their_names_name() { + let files = ["Ball_normal.png", "Ball_world_normal.png", "base-AO.png", "Base_curvature.png", "Ball_diffuse.png", "Head_ao.png", "Base_id.png"]; + let dir = bake_folder("sets", &files); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + + let result = import(&mut s, &dir, &files.map(|f| (f, None))); + + let assigned = &result["assigned"]; + assert_eq!(file_names(assigned).len(), 5, "{result}"); + for (ts, map) in [(0, BakedMap::Normal), (0, BakedMap::WorldNormal), (1, BakedMap::AmbientOcclusion), (1, BakedMap::Curvature), (1, BakedMap::Id)] { + assert!(has_map(&s, ts, map), "set {ts} lacks {}", map.id()); + assert!(assigned.as_array().unwrap().iter().any(|a| a["ts"] == ts && a["map"] == map.id()), "{result}"); + } + assert_eq!(file_names(&result["unmatched"]), ["Ball_diffuse.png", "Head_ao.png"]); + assert_eq!(s.undo_label(), Some("Import baked maps")); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.undo_label().map(str::to_string), label_before, "one undo step"); + assert!(s.doc.baked.values().all(|b| b.maps.is_empty()), "undo removes every imported map"); + assert!(s.doc.resources.is_empty(), "undo removes the imported images"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_given_map_overrides_the_name() { + let dir = bake_folder("override", &["Ball_bake3.png", "Base_normal.png"]); + let mut s = session(); + + let result = import(&mut s, &dir, &[("Ball_bake3.png", Some("thickness")), ("Base_normal.png", Some("height"))]); + + assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); + assert!(has_map(&s, 0, BakedMap::Thickness)); + assert!(has_map(&s, 1, BakedMap::Height)); + assert!(!has_map(&s, 1, BakedMap::Normal)); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_second_file_for_one_slot_is_left_out() { + let dir = bake_folder("twice", &["Ball_ao.png", "Ball_occlusion.png"]); + let mut s = session(); + + let result = import(&mut s, &dir, &[("Ball_ao.png", None), ("Ball_occlusion.png", None)]); + + assert_eq!(file_names(&result["assigned"]), ["Ball_ao.png"]); + assert_eq!(file_names(&result["unmatched"]), ["Ball_occlusion.png"]); + assert_eq!(s.doc.resources.len(), 1, "the left-out file is not imported"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_failed_file_imports_nothing() { + let dir = bake_folder("failed", &["Ball_ao.png"]); + std::fs::write(dir.join("Base_ao.png"), b"not an image").unwrap(); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + let files = json!({"files": [{"path": dir.join("Ball_ao.png").display().to_string()}, {"path": dir.join("Base_ao.png").display().to_string()}]}); + + let error = execute(&mut s, "textureSet.meshMap.import", &files).unwrap_err().to_string(); + + assert!(error.contains("Base_ao.png"), "{error}"); + assert!(s.doc.baked.values().all(|b| b.maps.is_empty())); + assert!(s.doc.resources.is_empty() && s.images.is_empty()); + assert_eq!(s.undo_label().map(str::to_string), label_before); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_uv_tiled_set_takes_one_file_per_tile() { + let dir = bake_folder("tiles", &["Plane_ao.1001.png", "Plane_ao.1002.png"]); + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + + let result = import(&mut s, &dir, &[("Plane_ao.1001.png", None), ("Plane_ao.1002.png", None)]); + + assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); + let baked = &s.doc.baked[&0]; + let ao = &baked.maps[&BakedMap::AmbientOcclusion]; + let width = baked.resolution as usize; + let middle_row = ao.len() / width / 2 * width; + assert!(ao[middle_row + width / 4] < ao[middle_row + 3 * width / 4], "each tile reads its own file"); + std::fs::remove_dir_all(dir).ok(); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..e1746a31 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1035,4 +1035,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Advanced settings", "إعدادات متقدمة"), + ("Import baked maps", "استيراد خرائط مخبوزة"), + ("Name each file after its texture set, like Body_normal.png", "سمِّ كل ملف باسم مجموعة الخامات الخاصة به، مثل Body_normal.png"), + ("Add...", "إضافة..."), + ("Imported {count} baked maps", "تم استيراد {count} من الخرائط المخبوزة"), + ("Not imported: {files}", "لم يتم استيرادها: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..1b86b2e7 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1078,4 +1078,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Auflösungsüberschreibung entfernen"), ("Texture set resolution", "Auflösung des Textursets"), ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ("Advanced settings", "Erweiterte Einstellungen"), + ("Import baked maps", "Gebackene Maps importieren"), + ("Name each file after its texture set, like Body_normal.png", "Benennen Sie jede Datei nach ihrem Texturset, z. B. Body_normal.png"), + ("Add...", "Hinzufügen..."), + ("Imported {count} baked maps", "{count} gebackene Maps importiert"), + ("Not imported: {files}", "Nicht importiert: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..a0445eed 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1063,4 +1063,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Quitar resolución personalizada"), ("Texture set resolution", "Resolución del conjunto de texturas"), ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ("Advanced settings", "Ajustes avanzados"), + ("Import baked maps", "Importar mapas horneados"), + ("Name each file after its texture set, like Body_normal.png", "Nombra cada archivo según su conjunto de texturas, p. ej. Body_normal.png"), + ("Add...", "Añadir..."), + ("Imported {count} baked maps", "{count} mapas horneados importados"), + ("Not imported: {files}", "Sin importar: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..235bf5a9 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1087,4 +1087,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Supprimer la résolution personnalisée"), ("Texture set resolution", "Résolution de l'ensemble de textures"), ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ("Advanced settings", "Paramètres avancés"), + ("Import baked maps", "Importer des cartes précalculées"), + ("Name each file after its texture set, like Body_normal.png", "Nommez chaque fichier d'après son ensemble de textures, par ex. Body_normal.png"), + ("Add...", "Ajouter..."), + ("Imported {count} baked maps", "{count} cartes précalculées importées"), + ("Not imported: {files}", "Non importés : {files}"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..12a180ed 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1072,4 +1072,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Rimuovi risoluzione personalizzata"), ("Texture set resolution", "Risoluzione del set di texture"), ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ("Advanced settings", "Impostazioni avanzate"), + ("Import baked maps", "Importa mappe bake"), + ("Name each file after its texture set, like Body_normal.png", "Dai a ogni file il nome del suo set di texture, ad es. Body_normal.png"), + ("Add...", "Aggiungi..."), + ("Imported {count} baked maps", "{count} mappe bake importate"), + ("Not imported: {files}", "Non importati: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..8b930774 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1057,4 +1057,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Advanced settings", "詳細設定"), + ("Import baked maps", "ベイク済みマップを読み込む"), + ("Name each file after its texture set, like Body_normal.png", "各ファイル名をテクスチャセット名で始めてください(例: Body_normal.png)"), + ("Add...", "追加..."), + ("Imported {count} baked maps", "ベイク済みマップを {count} 個読み込みました"), + ("Not imported: {files}", "読み込まれなかったファイル: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..30d5eef5 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1045,4 +1045,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Advanced settings", "고급 설정"), + ("Import baked maps", "베이크된 맵 가져오기"), + ("Name each file after its texture set, like Body_normal.png", "각 파일 이름을 텍스처 세트 이름으로 시작하세요(예: Body_normal.png)"), + ("Add...", "추가..."), + ("Imported {count} baked maps", "베이크된 맵 {count}개를 가져왔습니다"), + ("Not imported: {files}", "가져오지 않음: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..330c09a3 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1060,4 +1060,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Remover resolução personalizada"), ("Texture set resolution", "Resolução do conjunto de texturas"), ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ("Advanced settings", "Configurações avançadas"), + ("Import baked maps", "Importar mapas com bake"), + ("Name each file after its texture set, like Body_normal.png", "Nomeie cada arquivo com o nome do seu conjunto de texturas, como Body_normal.png"), + ("Add...", "Adicionar..."), + ("Imported {count} baked maps", "{count} mapas com bake importados"), + ("Not imported: {files}", "Não importados: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..f0731a7c 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1003,4 +1003,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Advanced settings", "高级设置"), + ("Import baked maps", "导入已烘焙贴图"), + ("Name each file after its texture set, like Body_normal.png", "以纹理集名称为每个文件命名,例如 Body_normal.png"), + ("Add...", "添加..."), + ("Imported {count} baked maps", "已导入 {count} 张烘焙贴图"), + ("Not imported: {files}", "未导入:{files}"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..23f67ca9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -19,6 +19,7 @@ pub mod keymap; mod mask_preview_image; mod mask_shape; pub mod menus; +pub mod new_project_advanced; pub mod parity; mod preview_image; mod preview_request; diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs new file mode 100644 index 00000000..50dd64c6 --- /dev/null +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -0,0 +1,155 @@ +//! New project ▸ Advanced settings: the normal map format, and baked map files imported at creation + +use egui::{RichText, Sense, Ui, vec2}; +use serde_json::{Value, json}; +use texturecraft_engine::core::NormalFormat; +use texturecraft_engine::template_cmds::builtin_templates; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::state::NewProject; +use crate::theme::{Tokens, caption}; +use crate::widgets::{section, section_chevron}; +use crate::windows::file_dialogs_available; + +/// Labels of every New project form row, so Basic and Advanced share one label column +const FORM_LABELS: [&str; 6] = ["3D mesh", "Project template", "Document resolution", "UV tiles (UDIM)", "Name", "Normal map format"]; + +/// Each normal map format with its command id and label +const NORMAL_FORMATS: [(NormalFormat, &str, &str); 2] = [(NormalFormat::OpenGl, "openGl", "OpenGL"), (NormalFormat::DirectX, "directX", "DirectX")]; + +/// Width of the dialog's dropdowns +const COMBO_WIDTH: f32 = 200.0; + +/// Width of the Add... and Clear buttons +const FILE_BUTTON_WIDTH: f32 = 96.0; + +/// Tallest the list of added files grows before it scrolls +const FILE_LIST_HEIGHT: f32 = 160.0; + +/// Width of the widest form label, for the label column of every form grid in the dialog +pub(crate) fn form_label_width(ui: &Ui) -> f32 { + let font = egui::TextStyle::Body.resolve(ui.style()); + FORM_LABELS.iter().map(|label| ui.painter().layout_no_wrap(tr(label).to_string(), font.clone(), egui::Color32::WHITE).size().x).fold(0.0, f32::max) +} + +/// The collapsible Advanced settings section (closed until opened) +pub(crate) fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { + let id = ui.make_persistent_id("np_advanced"); + let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, false); + let header = ui + .horizontal(|ui| { + ui.add(egui::Label::new(section_chevron(ui, state.is_open())).selectable(false)); + ui.add(egui::Label::new(caption(tr("Advanced settings"))).selectable(false)); + }) + .response + .interact(Sense::click()); + if header.clicked() { + state.toggle(ui); + } + + state.show_body_unindented(ui, |ui| { + egui::Grid::new("np_advanced_grid").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(form_label_width(ui)).show(ui, |ui| { + ui.label(tr("Normal map format")); + normal_format_combo(app, ui); + ui.end_row(); + }); + if file_dialogs_available() { + ui.add_space(4.0); + section(ui, "np_baked_maps", tr("Import baked maps"), false, |ui| baked_maps(&mut app.ui.new_project, ui)); + } + }); +} + +fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { + let new_project = &mut app.ui.new_project; + let user_templates = app.session.templates.list.iter().cloned(); + let template_format = + builtin_templates().into_iter().chain(user_templates).find(|t| t.name == new_project.template).map(|t| t.normal_format).unwrap_or_default(); + let current = new_project.normal_format.unwrap_or(template_format); + let current_label = NORMAL_FORMATS.iter().find(|(format, _, _)| *format == current).map_or("", |(_, _, label)| label); + egui::ComboBox::from_id_salt("np_normal_format").width(COMBO_WIDTH).selected_text(current_label).show_ui(ui, |ui| { + for (format, _, label) in NORMAL_FORMATS { + if ui.selectable_label(format == current, label).clicked() { + new_project.normal_format = Some(format); + } + } + }); +} + +fn baked_maps(new_project: &mut NewProject, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + let buttons_width = 2.0 * FILE_BUTTON_WIDTH + ui.spacing().item_spacing.x; + let hint_width = (ui.available_width() - buttons_width - ui.spacing().item_spacing.x).max(0.0); + ui.allocate_ui_with_layout(vec2(hint_width, 0.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(hint_width); + ui.add(egui::Label::new(RichText::new(tr("Name each file after its texture set, like Body_normal.png")).color(tokens.text_dim)).wrap()); + }); + if ui.add(egui::Button::new(tr("Add...")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + add_baked_map_files(new_project, pick_baked_map_files()); + } + if ui.add_enabled(!new_project.baked_maps.is_empty(), egui::Button::new(tr("Clear")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + new_project.baked_maps.clear(); + } + }); + if new_project.baked_maps.is_empty() { + return; + } + + ui.add_space(4.0); + egui::ScrollArea::vertical().max_height(FILE_LIST_HEIGHT).auto_shrink([false, true]).show(ui, |ui| { + for path in &new_project.baked_maps { + ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); + } + }); +} + +/// List picked baked map files (files already listed are skipped) +pub fn add_baked_map_files(new_project: &mut NewProject, paths: Vec) { + for path in paths { + if !new_project.baked_maps.contains(&path) { + new_project.baked_maps.push(path); + } + } +} + +/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome +pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewProject) { + let chosen_format = new_project.normal_format.filter(|format| *format != app.session.doc.project.normal_format); + if let Some((_, id, _)) = chosen_format.and_then(|chosen| NORMAL_FORMATS.iter().find(|(format, _, _)| *format == chosen)) { + app.run("textureSet.settings", json!({ "normalFormat": id })); + } + if new_project.baked_maps.is_empty() { + return; + } + + let files: Vec = new_project.baked_maps.iter().map(|path| json!({ "path": path })).collect(); + let Some(result) = app.run("textureSet.meshMap.import", json!({ "files": files })) else { + return; + }; + + let assigned = result["assigned"].as_array().map_or(0, Vec::len); + let not_imported: Vec = result["unmatched"].as_array().into_iter().flatten().filter_map(Value::as_str).map(file_name).collect(); + let mut text = trf("Imported {count} baked maps", &[("count", &assigned)]); + if !not_imported.is_empty() { + text.push('\n'); + text.push_str(&trf("Not imported: {files}", &[("files", ¬_imported.join(", "))])); + } + app.toast(text, !not_imported.is_empty()); +} + +fn file_name(path: &str) -> String { + std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |name| name.to_string_lossy().into_owned()) +} + +#[cfg(not(target_arch = "wasm32"))] +fn pick_baked_map_files() -> Vec { + let files = rfd::FileDialog::new().add_filter(tr("Images"), crate::web_files::IMAGE_EXTS).pick_files(); + files.unwrap_or_default().into_iter().map(|path| path.display().to_string()).collect() +} + +#[cfg(target_arch = "wasm32")] +fn pick_baked_map_files() -> Vec { + Vec::new() +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..f22d1d69 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1,7 +1,7 @@ //! UI state (serde, so the control channel can read and drive it). use serde::{Deserialize, Serialize}; -use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::core::{BakedMap, Channel, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; @@ -151,6 +151,12 @@ pub struct NewProject { /// Name typed to save the current project's settings as a template. #[serde(skip)] pub template_name: String, + /// Normal map format of the project and its imported normal maps; None keeps the template's + #[serde(default)] + pub normal_format: Option, + /// Baked map files to import at creation, matched to sets and mesh maps by name (desktop only) + #[serde(skip)] + pub baked_maps: Vec, } fn default_template() -> String { @@ -167,6 +173,8 @@ impl Default for NewProject { uv_tiles: None, template: default_template(), template_name: String::new(), + normal_format: None, + baked_maps: Vec::new(), } } } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 0c35d957..8ac07749 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -392,7 +392,7 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut create = false; dialog("new_project", tr("New project"), &mut open).show(ctx, |ui| { ui.label(caption(tr("Basic settings"))); - egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { + egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(crate::new_project_advanced::form_label_width(ui)).show(ui, |ui| { ui.label(tr("3D mesh")); ui.horizontal(|ui| { let label = app.ui.new_project.file.clone().unwrap_or_else(|| { @@ -429,6 +429,7 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if ui.selectable_label(t.name == np.template, &t.name).clicked() { np.template = t.name.clone(); np.resolution = t.resolution; + np.normal_format = None; } } }); @@ -469,6 +470,8 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); }); ui.add_space(8.0); + crate::new_project_advanced::advanced_settings(app, ui); + ui.add_space(8.0); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.add(primary_button(ui, tr("Create"))).clicked() { @@ -490,6 +493,8 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if r.is_some() { app.ui.windows.new_project = false; app.ui.mode = Mode::Painting; + app.ui.new_project.baked_maps.clear(); + crate::new_project_advanced::apply_after_create(app, &np); } } if !open { diff --git a/crates/ui-egui/tests/new_project_baked_maps.rs b/crates/ui-egui/tests/new_project_baked_maps.rs new file mode 100644 index 00000000..a2c95e98 --- /dev/null +++ b/crates/ui-egui/tests/new_project_baked_maps.rs @@ -0,0 +1,80 @@ +//! New project ▸ Import baked maps: added files are listed, Clear empties the list, Create imports them + +use std::path::PathBuf; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakedMap, NormalFormat}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::new_project_advanced::add_baked_map_files; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.windows.new_project = true; + h.state_mut().ui.new_project.resolution = 256; + h.run_steps(3); + h.get_by_label("Advanced settings").click(); + h.run_steps(3); + h.get_by_label("Import baked maps").click(); + h.run_steps(3); + h +} + +/// 4×4 PNGs named `files` in a fresh folder, as their full paths +fn bake_files(test: &str, files: &[&str]) -> Vec { + let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + files + .iter() + .map(|file| { + let path: PathBuf = dir.join(file); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 255, 255])).save(&path).unwrap(); + path.display().to_string() + }) + .collect() +} + +#[test] +fn added_files_are_listed_once_and_clear_empties_the_list() { + let mut h = harness(); + let paths = bake_files("list", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + + add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone()); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.run_steps(3); + + assert_eq!(h.state().ui.new_project.baked_maps.len(), 3, "each file once"); + for file in ["Ball_normal.png", "Base_ao.png", "Ball_notes.png"] { + h.get_by_label(file); + } + + h.get_by_label("Clear").click(); + h.run_steps(3); + assert!(h.state().ui.new_project.baked_maps.is_empty()); + assert!(h.query_by_label("Ball_normal.png").is_none()); +} + +#[test] +fn create_imports_the_listed_maps_in_the_chosen_normal_format() { + let mut h = harness(); + let paths = bake_files("create", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.state_mut().ui.new_project.normal_format = Some(NormalFormat::DirectX); + h.run_steps(3); + + h.get_by_label("Create").click(); + h.run_steps(3); + + let state = h.state(); + assert!(!state.ui.windows.new_project, "the dialog closes"); + let project = &state.session.doc.project; + assert_eq!(project.normal_format, NormalFormat::DirectX); + let baked = |ts: usize, map: BakedMap| state.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)); + assert!(baked(0, BakedMap::Normal) && baked(1, BakedMap::AmbientOcclusion)); + assert_eq!(state.session.doc.resources.len(), 2, "the file naming no map is not imported"); + let toast = &state.toasts.last().unwrap().text; + assert!(toast.contains("Imported 2 baked maps") && toast.contains("Ball_notes.png"), "{toast}"); + assert!(state.ui.new_project.baked_maps.is_empty(), "the next new project starts with no files"); + assert_eq!(state.session.undo_label(), Some("Import baked maps")); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 78707aa1..734036ca 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -170,7 +170,7 @@ takes a font family, not a path: it reads only the system's font folders. | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | | `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | -| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot) | +| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); many baked map files at once, matched to sets and maps by file name: `textureSet.meshMap.import {files: [{path, map?}]}` | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | | `material_load` | `{path}` | Add a `.tcmat` smart material, a MaterialCraft `.mcmat` material or a `.mcraft` package above the selection | | `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root | From ffe8587e541792eb356226b6cc476e1c3bc4a56e Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 08:25:04 +0000 Subject: [PATCH 37/73] Take &Path in the import test helper --- crates/engine/tests/meshmap_import.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/meshmap_import.rs b/crates/engine/tests/meshmap_import.rs index 62a983d6..da3cb780 100644 --- a/crates/engine/tests/meshmap_import.rs +++ b/crates/engine/tests/meshmap_import.rs @@ -1,6 +1,6 @@ //! Importing baked map files at once: each lands in the texture set and mesh map its name names -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use serde_json::{Value, json}; use texturecraft_engine::core::BakedMap; @@ -23,7 +23,7 @@ fn bake_folder(test: &str, files: &[&str]) -> PathBuf { dir } -fn import(s: &mut Session, dir: &PathBuf, files: &[(&str, Option<&str>)]) -> Value { +fn import(s: &mut Session, dir: &Path, files: &[(&str, Option<&str>)]) -> Value { let files: Vec = files .iter() .map(|(file, map)| { From 6eed52435db0ff1dfc05ff16e38ae51a8ae647f6 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 09:14:35 +0000 Subject: [PATCH 38/73] Match UV tiles per file, skip empty imports, review cleanups - Each tiled file is keyed by its own tile number and its image passed to use_images, so tiles named differently or renamed on import still match - Files of a tiled set without one of its tiles, and maps missing a tile, go to unmatched instead of failing the import - Nothing to import leaves no undo step - The map is read from the file name after the set name - Toast counts maps; a failed import keeps the file list - Cap the bytes one import reads; whole-method cleanup of set, use_images, tile_images and new_project --- crates/engine/src/meshmap_cmds.rs | 79 +++++++++++------- crates/engine/src/meshmap_file_name.rs | 72 ++++++++-------- crates/engine/src/meshmap_import_cmds.rs | 83 +++++++++++++------ crates/engine/src/resource_cmds.rs | 2 +- crates/engine/tests/meshmap_import.rs | 68 +++++++++++---- crates/ui-egui/src/i18n/ar.rs | 2 +- crates/ui-egui/src/i18n/de.rs | 2 +- crates/ui-egui/src/i18n/es.rs | 2 +- crates/ui-egui/src/i18n/fr.rs | 2 +- crates/ui-egui/src/i18n/it.rs | 2 +- crates/ui-egui/src/i18n/ja.rs | 2 +- crates/ui-egui/src/i18n/ko.rs | 2 +- crates/ui-egui/src/i18n/pt_br.rs | 2 +- crates/ui-egui/src/i18n/zh_hans.rs | 2 +- crates/ui-egui/src/new_project_advanced.rs | 20 +++-- crates/ui-egui/src/windows.rs | 56 +++++++------ .../ui-egui/tests/new_project_baked_maps.rs | 10 ++- 17 files changed, 258 insertions(+), 150 deletions(-) diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 932ba137..ac9003b7 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -38,58 +38,81 @@ fn set(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, CMD)?; let map = map_param(p, CMD)?; let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?; - let resolution = s.edit("Use image as mesh map", |s| use_image(s, CMD, ts, map, name))?; + let image = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?; + let texture_set = s.doc.project.texture_set(ts)?; + let images = match texture_set.tile_grid() { + Some(_) => tile_images(&s.images, CMD, name, &texture_set.uv_tiles)?, + None => BTreeMap::from([(FIRST_TILE, image)]), + }; + + let resolution = s.edit("Use image as mesh map", |s| use_images(s, CMD, ts, map, &images))?; Ok(json!({ "map": map.id(), "resolution": resolution })) } -/// Use image resource `name` as mesh map `map` of set `ts` inside the caller's edit; returns the map width -pub(crate) fn use_image(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, name: &str) -> Result { - let img = s.images.get(name).cloned().ok_or_else(|| bad(cmd, format!("no image resource `{name}`")))?; - let set = s.doc.project.texture_set(ts)?.clone(); - let tiles = set.tile_grid().map(|grid| tile_images(&s.images, cmd, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?; +/// The tile number a set without UV tiles keys its one image by +pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); - // Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile) - let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows)); - let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) { - Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))), - None => { - let (width, height) = set.bake.common.output_size(); - (width.saturating_mul(cols), height.saturating_mul(rows)) - } - }; - if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) { - return Err(bad(cmd, format!("mesh map size {res} × {height} is too large or empty"))); +/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width +pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let texture_set = s.doc.project.texture_set(ts)?; + let grid = texture_set.tile_grid(); + if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { + return Err(bad(cmd, format!("no image for UV tile {tile}"))); } - let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; - let data = match &tiles { - None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)), + // Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile) + let (columns, rows) = grid.map_or((1, 1), |grid| (grid.cols, grid.rows)); + let (width, height) = match s.doc.baked.get(&ts).filter(|baked| !baked.maps.is_empty()) { + Some(baked) => (baked.resolution, baked.maps.keys().next().map_or(baked.resolution, |other| baked.height(*other))), + None => { + let (width, height) = texture_set.bake.common.output_size(); + (width.saturating_mul(columns), height.saturating_mul(rows)) + } + }; + let empty = width == 0 || height == 0; + let too_many_texels = u64::from(width) * u64::from(height) > texturecraft_bake::MAX_TEXELS; + let too_wide = grid.is_none() && width > MAX_RESOLUTION; + if empty || too_many_texels || too_wide { + return Err(bad(cmd, format!("mesh map size {width} × {height} is too large or empty"))); + } + + let flip_green = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; + let data = match (grid, images.values().next()) { + (_, None) => return Err(bad(cmd, "no image to use")), + (None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)), // An atlas texel reads the image of the tile its mesh UV falls in - Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| { + (Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| { let uv = grid.from_atlas([u, v]); - udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) + udim_at(uv).and_then(|tile| images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) }), }; let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = res; + entry.resolution = width; entry.maps.insert(map, Arc::new(data)); s.doc.project.texture_set_mut(ts)?.baked.insert(map); - Ok(res) + Ok(width) } /// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for each tile's fn tile_images(images: &ImageStore, cmd: &str, name: &str, tiles: &[u32]) -> Result>> { - let at = udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; + let tile_at = + udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; + let (before_tile, after_tile) = (name.get(..tile_at).unwrap_or_default(), name.get(tile_at + 4..).unwrap_or_default()); tiles .iter() - .map(|&t| { - let tile_name = format!("{}{t}{}", name.get(..at).unwrap_or_default(), name.get(at + 4..).unwrap_or_default()); - images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {t}"))) + .map(|&tile| { + let tile_name = format!("{before_tile}{tile}{after_tile}"); + images.get(&tile_name).cloned().map(|image| (tile, image)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {tile}"))) }) .collect() } +/// The UV tile number in a file name (`Body_ao.1002.png` → 1002) +pub(crate) fn tile_number(file_name: &str) -> Option { + udim_in(file_name).and_then(|at| file_name.get(at..at + 4)).and_then(|digits| digits.parse().ok()) +} + /// Where the last UDIM tile number (four digits alone, in [`UDIM_RANGE`]) in `name` starts. fn udim_in(name: &str) -> Option { let b = name.as_bytes(); diff --git a/crates/engine/src/meshmap_file_name.rs b/crates/engine/src/meshmap_file_name.rs index cfc4f125..fde32d5e 100644 --- a/crates/engine/src/meshmap_file_name.rs +++ b/crates/engine/src/meshmap_file_name.rs @@ -5,13 +5,14 @@ use std::path::Path; use texturecraft_core::{BakedMap, UDIM_RANGE}; /// Mesh maps named by two words anywhere in the file name; they win over the one-word names -const TWO_WORD_NAMES: [(&str, &[&str], BakedMap); 3] = [ +const TWO_WORD_NAMES: &[(&str, &[&str], BakedMap)] = &[ ("world", &["normal", "normals"], BakedMap::WorldNormal), ("bent", &["normal", "normals"], BakedMap::BentNormal), ("ambient", &["occlusion"], BakedMap::AmbientOcclusion), ]; -const ONE_WORD_NAMES: [(&str, BakedMap); 20] = [ +/// Mesh maps named by one word, including the two-word names written as one +const ONE_WORD_NAMES: &[(&str, BakedMap)] = &[ ("worldnormal", BakedMap::WorldNormal), ("worldnormals", BakedMap::WorldNormal), ("bentnormal", BakedMap::BentNormal), @@ -38,29 +39,33 @@ fn is_separator(c: char) -> bool { matches!(c, '_' | '-' | '.' | ' ') } -/// The file name without its folder and extension -fn stem(path: &str) -> &str { - Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or_default() +/// The lowercase file name without its folder and extension +fn lowercase_stem(path: &str) -> String { + Path::new(path).file_stem().and_then(|stem| stem.to_str()).unwrap_or_default().to_lowercase() } -/// The lowercase words of a file name, without UV tile numbers (`Body_AO.1001` → body, ao) -fn words(path: &str) -> Vec { - stem(path) - .split(is_separator) - .filter(|w| !w.is_empty() && !w.parse::().is_ok_and(|n| w.len() == 4 && UDIM_RANGE.contains(&n))) - .map(str::to_lowercase) - .collect() +/// What follows `set_name` at the start of a lowercase stem, when a separator follows it +fn after_set_name<'a>(stem: &'a str, set_name: &str) -> Option<&'a str> { + if set_name.is_empty() { + return None; + } + + stem.strip_prefix(&set_name.to_lowercase()).filter(|rest| rest.starts_with(is_separator)) } -/// The mesh map a file holds, from the words of its name; the last recognised word wins -pub(crate) fn baked_map_from_file_name(path: &str) -> Option { - let words = words(path); - let has = |word: &str| words.iter().any(|w| w == word); +/// The mesh map a file holds, from the words of its name after `set_name`; the last recognised word wins +pub(crate) fn baked_map_from_file_name(path: &str, set_name: &str) -> Option { + let stem = lowercase_stem(path); + let rest = after_set_name(&stem, set_name).unwrap_or(&stem); + let is_tile_number = |word: &str| word.len() == 4 && word.parse::().is_ok_and(|number| UDIM_RANGE.contains(&number)); + let words: Vec<&str> = rest.split(is_separator).filter(|word| !word.is_empty() && !is_tile_number(word)).collect(); + + let has = |name: &str| words.contains(&name); TWO_WORD_NAMES .iter() - .find(|(first, seconds, _)| has(first) && seconds.iter().any(|s| has(s))) + .find(|(first, seconds, _)| has(first) && seconds.iter().any(|second| has(second))) .map(|(_, _, map)| *map) - .or_else(|| words.iter().rev().find_map(|w| ONE_WORD_NAMES.iter().find(|(name, _)| name == w).map(|(_, map)| *map))) + .or_else(|| words.iter().rev().find_map(|word| ONE_WORD_NAMES.iter().find(|(name, _)| name == word).map(|(_, map)| *map))) } /// The set a file is for: the longest set name its name starts with before a separator (any name with one set) @@ -69,14 +74,8 @@ pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Opti return Some(0); } - let stem = stem(path).to_lowercase(); - set_names - .iter() - .enumerate() - .filter(|(_, name)| !name.is_empty()) - .filter(|(_, name)| stem.strip_prefix(&name.to_lowercase()).and_then(|rest| rest.chars().next()).is_some_and(is_separator)) - .max_by_key(|(_, name)| name.chars().count()) - .map(|(ts, _)| ts) + let stem = lowercase_stem(path); + set_names.iter().enumerate().filter(|(_, name)| after_set_name(&stem, name).is_some()).max_by_key(|(_, name)| name.chars().count()).map(|(ts, _)| ts) } #[cfg(test)] @@ -109,23 +108,30 @@ mod tests { ("Body_alpha.png", BakedMap::Opacity), ]; for (file, map) in cases { - assert_eq!(baked_map_from_file_name(file), Some(map), "{file}"); + assert_eq!(baked_map_from_file_name(file, "Body"), Some(map), "{file}"); } } #[test] fn tile_numbers_and_folders_are_ignored() { - assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png"), Some(BakedMap::AmbientOcclusion)); - assert_eq!(baked_map_from_file_name("Body_normal_1002.tga"), Some(BakedMap::Normal)); + assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png", "Body"), Some(BakedMap::AmbientOcclusion)); + assert_eq!(baked_map_from_file_name("Body_normal_1002.tga", "Body"), Some(BakedMap::Normal)); assert_eq!(texture_set_from_file_name("/bakes/Body_ao.1001.png", &["Head", "Body"]), Some(1)); } #[test] fn unknown_words_match_no_map() { - assert_eq!(baked_map_from_file_name("Body_diffuse.png"), None); - assert_eq!(baked_map_from_file_name("Body_1001.png"), None); - assert_eq!(baked_map_from_file_name("ambient.png"), None); - assert_eq!(baked_map_from_file_name(""), None); + assert_eq!(baked_map_from_file_name("Body_diffuse.png", "Body"), None); + assert_eq!(baked_map_from_file_name("Body_1001.png", "Body"), None); + assert_eq!(baked_map_from_file_name("ambient.png", "Body"), None); + assert_eq!(baked_map_from_file_name("", "Body"), None); + } + + #[test] + fn the_set_name_is_not_read_as_a_map() { + assert_eq!(baked_map_from_file_name("World_normal.png", "World"), Some(BakedMap::Normal)); + assert_eq!(baked_map_from_file_name("ID_diffuse.png", "ID"), None); + assert_eq!(baked_map_from_file_name("Body_ao.png", ""), Some(BakedMap::AmbientOcclusion)); } #[test] diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs index 9770cf63..f8ea8244 100644 --- a/crates/engine/src/meshmap_import_cmds.rs +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -1,20 +1,24 @@ //! Import mesh maps baked in another app: many files at once, each to the set and slot its file name names use std::collections::BTreeMap; +use std::path::Path; use serde_json::{Value, json}; use texturecraft_core::BakedMap; use crate::commands::{CommandSpec, always, bad, strp}; -use crate::meshmap_cmds::use_image; +use crate::meshmap_cmds::{FIRST_TILE, tile_number, use_images}; use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name}; use crate::resource_cmds::read_image_file; use crate::{Result, Session, cmd}; const CMD: &str = "textureSet.meshMap.import"; -/// Most files one import takes -const MAX_FILES: usize = 1024; +/// Most files one import takes: every mesh map of dozens of sets, each split over a few UV tiles +const MAX_FILES: usize = 512; + +/// Most bytes one import reads, since every file stays decoded in memory until the import ends +const MAX_TOTAL_BYTES: u64 = 2 << 30; pub fn specs() -> Vec { vec![cmd!( @@ -22,7 +26,7 @@ pub fn specs() -> Vec { "Import baked maps", [], None, - "{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set: a UV-tiled set takes one file per tile (`Body_ao.1001.png`, `Body_ao.1002.png`). Files matching no set or map, and any file after the first for one slot, are left out and listed in `unmatched`. One undo step; desktop only", + "{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set. A UV-tiled set takes one file per tile, named with the tile number (`Body_ao.1001.png`, `Body_ao.1002.png`). Left out and listed in `unmatched`: files matching no set or map, a second file for one slot or tile, files of a UV-tiled set without one of its tile numbers, and every file of a map missing a tile. One undo step (none when nothing matches); desktop only", always, import )] @@ -34,39 +38,52 @@ fn import(s: &mut Session, p: &Value) -> Result { return Err(bad(CMD, format!("at most {MAX_FILES} files at once"))); } - let set_names: Vec = s.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); - let set_names: Vec<&str> = set_names.iter().map(String::as_str).collect(); - let mut slots: BTreeMap<(usize, BakedMap), Vec<&str>> = BTreeMap::new(); + let set_names: Vec<&str> = s.doc.project.texture_sets.iter().map(|set| set.name.as_str()).collect(); + let mut slots: BTreeMap<(usize, BakedMap), BTreeMap> = BTreeMap::new(); let mut unmatched = Vec::new(); for file in files { let path = strp(file, "path").ok_or_else(|| bad(CMD, "every file needs a `path`"))?; - let map = match strp(file, "map") { - Some(id) => Some(BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))?), - None => baked_map_from_file_name(path), - }; - match (texture_set_from_file_name(path, &set_names), map) { - (Some(ts), Some(map)) => slots.entry((ts, map)).or_default().push(path), + let given_map = strp(file, "map").map(|id| BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))).transpose()?; + match slot_of(s, &set_names, path, given_map) { + Some((slot, tile)) if !slots.get(&slot).is_some_and(|tiles| tiles.contains_key(&tile)) => { + slots.entry(slot).or_default().insert(tile, path); + } _ => unmatched.push(path), } } + // A UV-tiled map needs a file for every tile of its set + slots.retain(|(ts, _), tiles| { + let complete = + s.doc.project.texture_sets.get(*ts).is_some_and(|set| set.tile_grid().is_none() || set.uv_tiles.iter().all(|tile| tiles.contains_key(tile))); + if !complete { + unmatched.extend(tiles.values()); + } + complete + }); + if slots.is_empty() { + return Ok(json!({ "assigned": [], "unmatched": unmatched })); + } + let result = s.edit("Import baked maps", |s| { let mut assigned = Vec::new(); - for ((ts, map), paths) in &slots { - // A UV-tiled set reads every tile's file; any other set takes the first file for a slot - let files_used = if s.doc.project.texture_set(*ts)?.tile_grid().is_some() { paths.len() } else { 1 }; - let (taken, extra) = paths.split_at(files_used); - let mut image_name = None; - for path in taken { - let name = s.add_image_resource(path, read_image_file(CMD, path)?)?; - image_name.get_or_insert(name); - } - if let Some(name) = image_name { - use_image(s, CMD, *ts, *map, &name)?; - } + let mut total_bytes = 0; + for ((ts, map), tiles) in &slots { + let mut images = BTreeMap::new(); + for (tile, path) in tiles { + let bytes = read_image_file(CMD, path)?; + total_bytes += bytes.len() as u64; + if total_bytes > MAX_TOTAL_BYTES { + return Err(bad(CMD, format!("the files are larger than {} GB together", MAX_TOTAL_BYTES >> 30))); + } - assigned.extend(taken.iter().map(|path| json!({"path": path, "ts": ts, "map": map.id()}))); - unmatched.extend(extra); + let name = s.add_image_resource(path, bytes)?; + if let Some(image) = s.images.get(&name) { + images.insert(*tile, image.clone()); + } + assigned.push(json!({"path": path, "ts": ts, "map": map.id()})); + } + use_images(s, CMD, *ts, *map, &images)?; } Ok(assigned) }); @@ -77,3 +94,15 @@ fn import(s: &mut Session, p: &Value) -> Result { Ok(json!({ "assigned": result?, "unmatched": unmatched })) } + +/// The texture set and mesh map a file is for, and its UV tile ([`FIRST_TILE`] on a set without UV tiles) +fn slot_of(s: &Session, set_names: &[&str], path: &str, given_map: Option) -> Option<((usize, BakedMap), u32)> { + let ts = texture_set_from_file_name(path, set_names)?; + let map = given_map.or_else(|| baked_map_from_file_name(path, set_names.get(ts).copied().unwrap_or_default()))?; + let texture_set = s.doc.project.texture_sets.get(ts)?; + let tile = match texture_set.tile_grid() { + Some(_) => tile_number(Path::new(path).file_name()?.to_str()?).filter(|tile| texture_set.uv_tiles.contains(tile))?, + None => FIRST_TILE, + }; + Some(((ts, map), tile)) +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 74682be8..3dc415a4 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -36,7 +36,7 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { } impl Session { - /// Add an image resource from bytes (one undo step); returns its unique, sanitized name. + /// 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 { self.edit("Import resource", |s| s.add_image_resource(file_name, bytes)) } diff --git a/crates/engine/tests/meshmap_import.rs b/crates/engine/tests/meshmap_import.rs index da3cb780..d9ed53f1 100644 --- a/crates/engine/tests/meshmap_import.rs +++ b/crates/engine/tests/meshmap_import.rs @@ -17,7 +17,7 @@ fn bake_folder(test: &str, files: &[&str]) -> PathBuf { let dir = std::env::temp_dir().join(format!("texturecraft-meshmap-import-{test}-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); for (index, file) in files.iter().enumerate() { - let gray = 20 + 20 * index as u8; + let gray = u8::try_from(20 + 20 * index).unwrap_or(u8::MAX); image::RgbaImage::from_pixel(4, 4, image::Rgba([gray, gray, gray, 255])).save(dir.join(file)).unwrap(); } dir @@ -41,13 +41,13 @@ fn file_names(list: &Value) -> Vec { list.as_array() .unwrap() .iter() - .map(|v| v.as_str().map_or_else(|| v["path"].as_str().unwrap(), |p| p)) - .map(|p| p.rsplit(['/', '\\']).next().unwrap().to_string()) + .map(|entry| entry.as_str().unwrap_or_else(|| entry["path"].as_str().unwrap())) + .map(|path| path.rsplit(['/', '\\']).next().unwrap().to_string()) .collect() } fn has_map(s: &Session, ts: usize, map: BakedMap) -> bool { - s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map) + s.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map) } #[test] @@ -57,21 +57,21 @@ fn files_go_to_the_set_and_map_their_names_name() { let mut s = session(); let label_before = s.undo_label().map(str::to_string); - let result = import(&mut s, &dir, &files.map(|f| (f, None))); + let result = import(&mut s, &dir, &files.map(|file| (file, None))); let assigned = &result["assigned"]; assert_eq!(file_names(assigned).len(), 5, "{result}"); for (ts, map) in [(0, BakedMap::Normal), (0, BakedMap::WorldNormal), (1, BakedMap::AmbientOcclusion), (1, BakedMap::Curvature), (1, BakedMap::Id)] { assert!(has_map(&s, ts, map), "set {ts} lacks {}", map.id()); - assert!(assigned.as_array().unwrap().iter().any(|a| a["ts"] == ts && a["map"] == map.id()), "{result}"); + assert!(assigned.as_array().unwrap().iter().any(|entry| entry["ts"] == ts && entry["map"] == map.id()), "{result}"); } assert_eq!(file_names(&result["unmatched"]), ["Ball_diffuse.png", "Head_ao.png"]); assert_eq!(s.undo_label(), Some("Import baked maps")); execute(&mut s, "edit.undo", &Value::Null).unwrap(); assert_eq!(s.undo_label().map(str::to_string), label_before, "one undo step"); - assert!(s.doc.baked.values().all(|b| b.maps.is_empty()), "undo removes every imported map"); - assert!(s.doc.resources.is_empty(), "undo removes the imported images"); + assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty()), "undo removes every imported map"); + assert!(s.doc.resources.is_empty(), "undo removes the imported image resources"); std::fs::remove_dir_all(dir).ok(); } @@ -103,8 +103,8 @@ fn a_second_file_for_one_slot_is_left_out() { } #[test] -fn a_failed_file_imports_nothing() { - let dir = bake_folder("failed", &["Ball_ao.png"]); +fn an_undecodable_file_imports_nothing() { + let dir = bake_folder("undecodable", &["Ball_ao.png"]); std::fs::write(dir.join("Base_ao.png"), b"not an image").unwrap(); let mut s = session(); let label_before = s.undo_label().map(str::to_string); @@ -113,18 +113,24 @@ fn a_failed_file_imports_nothing() { let error = execute(&mut s, "textureSet.meshMap.import", &files).unwrap_err().to_string(); assert!(error.contains("Base_ao.png"), "{error}"); - assert!(s.doc.baked.values().all(|b| b.maps.is_empty())); + assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty())); assert!(s.doc.resources.is_empty() && s.images.is_empty()); assert_eq!(s.undo_label().map(str::to_string), label_before); std::fs::remove_dir_all(dir).ok(); } -#[test] -fn a_uv_tiled_set_takes_one_file_per_tile() { - let dir = bake_folder("tiles", &["Plane_ao.1001.png", "Plane_ao.1002.png"]); - let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); +/// The UV tile plane: one texture set "Plane" on tiles 1001 and 1002 +fn tiled_session() -> Session { + Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap() +} - let result = import(&mut s, &dir, &[("Plane_ao.1001.png", None), ("Plane_ao.1002.png", None)]); +#[test] +fn a_uv_tiled_set_takes_one_file_per_tile_however_each_is_written() { + let files = ["Plane_ao.1001.png", "plane-AO-1002.png"]; + let dir = bake_folder("tiles", &files); + let mut s = tiled_session(); + + let result = import(&mut s, &dir, &files.map(|file| (file, None))); assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); let baked = &s.doc.baked[&0]; @@ -134,3 +140,33 @@ fn a_uv_tiled_set_takes_one_file_per_tile() { assert!(ao[middle_row + width / 4] < ao[middle_row + 3 * width / 4], "each tile reads its own file"); std::fs::remove_dir_all(dir).ok(); } + +#[test] +fn tiled_files_without_their_tiles_are_left_out_alone() { + let files = ["Plane_ao.1001.png", "Plane_ao.1002.png", "Plane_normal.png", "Plane_curvature.1001.png", "Plane_id.1005.png"]; + let dir = bake_folder("partial-tiles", &files); + let mut s = tiled_session(); + + let result = import(&mut s, &dir, &files.map(|file| (file, None))); + + assert_eq!(file_names(&result["assigned"]), ["Plane_ao.1001.png", "Plane_ao.1002.png"]); + assert_eq!(file_names(&result["unmatched"]), ["Plane_normal.png", "Plane_id.1005.png", "Plane_curvature.1001.png"]); + assert!(has_map(&s, 0, BakedMap::AmbientOcclusion)); + assert_eq!(s.doc.resources.len(), 2, "left-out files are not imported"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn nothing_matched_makes_no_undo_step() { + let dir = bake_folder("none", &["Head_ao.png", "Ball_diffuse.png"]); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + + let result = import(&mut s, &dir, &[("Head_ao.png", None), ("Ball_diffuse.png", None)]); + + assert_eq!(file_names(&result["assigned"]), Vec::::new()); + assert_eq!(file_names(&result["unmatched"]).len(), 2); + assert_eq!(s.undo_label().map(str::to_string), label_before); + assert!(!s.modified); + std::fs::remove_dir_all(dir).ok(); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index e1746a31..6ed381eb 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1039,6 +1039,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "استيراد خرائط مخبوزة"), ("Name each file after its texture set, like Body_normal.png", "سمِّ كل ملف باسم مجموعة الخامات الخاصة به، مثل Body_normal.png"), ("Add...", "إضافة..."), - ("Imported {count} baked maps", "تم استيراد {count} من الخرائط المخبوزة"), + ("Baked maps imported: {count}", "الخرائط المخبوزة المستوردة: {count}"), ("Not imported: {files}", "لم يتم استيرادها: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 1b86b2e7..4d59f67f 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1082,6 +1082,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Gebackene Maps importieren"), ("Name each file after its texture set, like Body_normal.png", "Benennen Sie jede Datei nach ihrem Texturset, z. B. Body_normal.png"), ("Add...", "Hinzufügen..."), - ("Imported {count} baked maps", "{count} gebackene Maps importiert"), + ("Baked maps imported: {count}", "Gebackene Maps importiert: {count}"), ("Not imported: {files}", "Nicht importiert: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index a0445eed..f8b84617 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1067,6 +1067,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Importar mapas horneados"), ("Name each file after its texture set, like Body_normal.png", "Nombra cada archivo según su conjunto de texturas, p. ej. Body_normal.png"), ("Add...", "Añadir..."), - ("Imported {count} baked maps", "{count} mapas horneados importados"), + ("Baked maps imported: {count}", "Mapas horneados importados: {count}"), ("Not imported: {files}", "Sin importar: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 235bf5a9..b282f90b 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1091,6 +1091,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Importer des cartes précalculées"), ("Name each file after its texture set, like Body_normal.png", "Nommez chaque fichier d'après son ensemble de textures, par ex. Body_normal.png"), ("Add...", "Ajouter..."), - ("Imported {count} baked maps", "{count} cartes précalculées importées"), + ("Baked maps imported: {count}", "Cartes précalculées importées : {count}"), ("Not imported: {files}", "Non importés : {files}"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 12a180ed..5d937383 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1076,6 +1076,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Importa mappe bake"), ("Name each file after its texture set, like Body_normal.png", "Dai a ogni file il nome del suo set di texture, ad es. Body_normal.png"), ("Add...", "Aggiungi..."), - ("Imported {count} baked maps", "{count} mappe bake importate"), + ("Baked maps imported: {count}", "Mappe bake importate: {count}"), ("Not imported: {files}", "Non importati: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 8b930774..634660bd 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1061,6 +1061,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "ベイク済みマップを読み込む"), ("Name each file after its texture set, like Body_normal.png", "各ファイル名をテクスチャセット名で始めてください(例: Body_normal.png)"), ("Add...", "追加..."), - ("Imported {count} baked maps", "ベイク済みマップを {count} 個読み込みました"), + ("Baked maps imported: {count}", "読み込んだベイク済みマップ: {count}"), ("Not imported: {files}", "読み込まれなかったファイル: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 30d5eef5..cafc4b90 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1049,6 +1049,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "베이크된 맵 가져오기"), ("Name each file after its texture set, like Body_normal.png", "각 파일 이름을 텍스처 세트 이름으로 시작하세요(예: Body_normal.png)"), ("Add...", "추가..."), - ("Imported {count} baked maps", "베이크된 맵 {count}개를 가져왔습니다"), + ("Baked maps imported: {count}", "가져온 베이크된 맵: {count}"), ("Not imported: {files}", "가져오지 않음: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 330c09a3..f7779924 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1064,6 +1064,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Importar mapas com bake"), ("Name each file after its texture set, like Body_normal.png", "Nomeie cada arquivo com o nome do seu conjunto de texturas, como Body_normal.png"), ("Add...", "Adicionar..."), - ("Imported {count} baked maps", "{count} mapas com bake importados"), + ("Baked maps imported: {count}", "Mapas com bake importados: {count}"), ("Not imported: {files}", "Não importados: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index f0731a7c..83044fc3 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1007,6 +1007,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "导入已烘焙贴图"), ("Name each file after its texture set, like Body_normal.png", "以纹理集名称为每个文件命名,例如 Body_normal.png"), ("Add...", "添加..."), - ("Imported {count} baked maps", "已导入 {count} 张烘焙贴图"), + ("Baked maps imported: {count}", "已导入的烘焙贴图:{count}"), ("Not imported: {files}", "未导入:{files}"), ]; diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs index 50dd64c6..ae1993d1 100644 --- a/crates/ui-egui/src/new_project_advanced.rs +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -1,5 +1,7 @@ //! New project ▸ Advanced settings: the normal map format, and baked map files imported at creation +use std::collections::BTreeSet; + use egui::{RichText, Sense, Ui, vec2}; use serde_json::{Value, json}; use texturecraft_engine::core::NormalFormat; @@ -19,7 +21,7 @@ const FORM_LABELS: [&str; 6] = ["3D mesh", "Project template", "Document resolut const NORMAL_FORMATS: [(NormalFormat, &str, &str); 2] = [(NormalFormat::OpenGl, "openGl", "OpenGL"), (NormalFormat::DirectX, "directX", "DirectX")]; /// Width of the dialog's dropdowns -const COMBO_WIDTH: f32 = 200.0; +pub(crate) const COMBO_WIDTH: f32 = 200.0; /// Width of the Add... and Clear buttons const FILE_BUTTON_WIDTH: f32 = 96.0; @@ -64,8 +66,12 @@ pub(crate) fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { let new_project = &mut app.ui.new_project; let user_templates = app.session.templates.list.iter().cloned(); - let template_format = - builtin_templates().into_iter().chain(user_templates).find(|t| t.name == new_project.template).map(|t| t.normal_format).unwrap_or_default(); + let template_format = builtin_templates() + .into_iter() + .chain(user_templates) + .find(|template| template.name == new_project.template) + .map(|template| template.normal_format) + .unwrap_or_default(); let current = new_project.normal_format.unwrap_or(template_format); let current_label = NORMAL_FORMATS.iter().find(|(format, _, _)| *format == current).map_or("", |(_, _, label)| label); egui::ComboBox::from_id_salt("np_normal_format").width(COMBO_WIDTH).selected_text(current_label).show_ui(ui, |ui| { @@ -114,7 +120,7 @@ pub fn add_baked_map_files(new_project: &mut NewProject, paths: Vec) { } } -/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome +/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome; a failed import keeps the list pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewProject) { let chosen_format = new_project.normal_format.filter(|format| *format != app.session.doc.project.normal_format); if let Some((_, id, _)) = chosen_format.and_then(|chosen| NORMAL_FORMATS.iter().find(|(format, _, _)| *format == chosen)) { @@ -129,14 +135,16 @@ pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewPro return; }; - let assigned = result["assigned"].as_array().map_or(0, Vec::len); + let assigned = result["assigned"].as_array().into_iter().flatten(); + let maps: BTreeSet<(u64, &str)> = assigned.filter_map(|entry| Some((entry["ts"].as_u64()?, entry["map"].as_str()?))).collect(); let not_imported: Vec = result["unmatched"].as_array().into_iter().flatten().filter_map(Value::as_str).map(file_name).collect(); - let mut text = trf("Imported {count} baked maps", &[("count", &assigned)]); + let mut text = trf("Baked maps imported: {count}", &[("count", &maps.len())]); if !not_imported.is_empty() { text.push('\n'); text.push_str(&trf("Not imported: {files}", &[("files", ¬_imported.join(", "))])); } app.toast(text, !not_imported.is_empty()); + app.ui.new_project.baked_maps.clear(); } fn file_name(path: &str) -> String { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 8ac07749..4bd8197f 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -11,6 +11,7 @@ use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; use crate::i18n::LANGUAGES; use crate::i18n::{tr, trf}; +use crate::new_project_advanced::COMBO_WIDTH; use crate::state::Mode; use crate::theme::{Accent, Brightness, Tokens, caption}; use crate::widgets::{color_swatch, combo, icon_button, primary_button, slider, slider_edit}; @@ -388,6 +389,7 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.new_project { return; } + let mut open = true; let mut create = false; dialog("new_project", tr("New project"), &mut open).show(ctx, |ui| { @@ -399,13 +401,16 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { BUILTINS .iter() .find(|(id, _)| *id == app.ui.new_project.mesh) - .map(|(_, l)| trf("Built-in: {mesh}", &[("mesh", &tr(l))])) + .map(|(_, builtin_label)| trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))])) .unwrap_or_default() }); - egui::ComboBox::from_id_salt("np_mesh").width(200.0).selected_text(label).show_ui(ui, |ui| { - for (id, l) in BUILTINS { + egui::ComboBox::from_id_salt("np_mesh").width(COMBO_WIDTH).selected_text(label).show_ui(ui, |ui| { + for (id, builtin_label) in BUILTINS { if ui - .selectable_label(app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(), trf("Built-in: {mesh}", &[("mesh", &tr(l))])) + .selectable_label( + app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(), + trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))]), + ) .clicked() { app.ui.new_project.mesh = id.to_string(); @@ -415,21 +420,21 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { }); if file_dialogs_available() && ui.button(tr("Select...")).clicked() - && let Some(p) = pick_mesh_file() + && let Some(path) = pick_mesh_file() { - app.ui.new_project.file = Some(p); + app.ui.new_project.file = Some(path); } }); ui.end_row(); ui.label(tr("Project template")); - let np = &mut app.ui.new_project; - egui::ComboBox::from_id_salt("np_template").width(200.0).selected_text(np.template.clone()).show_ui(ui, |ui| { - let user = app.session.templates.list.iter(); - for t in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user) { - if ui.selectable_label(t.name == np.template, &t.name).clicked() { - np.template = t.name.clone(); - np.resolution = t.resolution; - np.normal_format = None; + let new_project = &mut app.ui.new_project; + egui::ComboBox::from_id_salt("np_template").width(COMBO_WIDTH).selected_text(new_project.template.clone()).show_ui(ui, |ui| { + let user_templates = app.session.templates.list.iter(); + for template in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user_templates) { + if ui.selectable_label(template.name == new_project.template, &template.name).clicked() { + new_project.template = template.name.clone(); + new_project.resolution = template.resolution; + new_project.normal_format = None; } } }); @@ -448,20 +453,20 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); ui.label(tr("Document resolution")); egui::ComboBox::from_id_salt("np_res").selected_text(format!("{0} x {0}", app.ui.new_project.resolution)).show_ui(ui, |ui| { - for r in [512u32, 1024, 2048, 4096] { - ui.selectable_value(&mut app.ui.new_project.resolution, r, format!("{r} x {r}")); + for size in [512u32, 1024, 2048, 4096] { + ui.selectable_value(&mut app.ui.new_project.resolution, size, format!("{size} x {size}")); } }); ui.end_row(); ui.label(tr("UV tiles (UDIM)")); - let tiles_label = |m: Option| match m { + let tiles_label = |tiles: Option| match tiles { None => tr("Automatic (from the mesh UVs)"), Some(true) => tr("On"), Some(false) => tr("Off"), }; egui::ComboBox::from_id_salt("np_tiles").selected_text(tiles_label(app.ui.new_project.uv_tiles)).show_ui(ui, |ui| { - for m in [None, Some(true), Some(false)] { - ui.selectable_value(&mut app.ui.new_project.uv_tiles, m, tiles_label(m)); + for tiles in [None, Some(true), Some(false)] { + ui.selectable_value(&mut app.ui.new_project.uv_tiles, tiles, tiles_label(tiles)); } }); ui.end_row(); @@ -484,17 +489,16 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); if create { - let np = app.ui.new_project.clone(); - let (cmd, mesh) = match &np.file { + let new_project = app.ui.new_project.clone(); + let (command, mesh) = match &new_project.file { Some(path) => ("file.new", path.clone()), - None => ("project.new", np.mesh.clone()), + None => ("project.new", new_project.mesh.clone()), }; - let r = app.run(cmd, json!({"mesh": mesh, "resolution": np.resolution, "name": np.name, "uvTiles": np.uv_tiles, "template": np.template})).map(|_| ()); - if r.is_some() { + let params = json!({"mesh": mesh, "resolution": new_project.resolution, "name": new_project.name, "uvTiles": new_project.uv_tiles, "template": new_project.template}); + if app.run(command, params).is_some() { app.ui.windows.new_project = false; app.ui.mode = Mode::Painting; - app.ui.new_project.baked_maps.clear(); - crate::new_project_advanced::apply_after_create(app, &np); + crate::new_project_advanced::apply_after_create(app, &new_project); } } if !open { diff --git a/crates/ui-egui/tests/new_project_baked_maps.rs b/crates/ui-egui/tests/new_project_baked_maps.rs index a2c95e98..5b1d7615 100644 --- a/crates/ui-egui/tests/new_project_baked_maps.rs +++ b/crates/ui-egui/tests/new_project_baked_maps.rs @@ -21,7 +21,7 @@ fn harness() -> Harness<'static, TextureCraftApp> { h } -/// 4×4 PNGs named `files` in a fresh folder, as their full paths +/// 4×4 PNGs named `files` in a fresh folder, as their full paths; green 0.2 shows which way a normal map was read fn bake_files(test: &str, files: &[&str]) -> Vec { let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -29,7 +29,7 @@ fn bake_files(test: &str, files: &[&str]) -> Vec { .iter() .map(|file| { let path: PathBuf = dir.join(file); - image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 255, 255])).save(&path).unwrap(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 51, 255, 255])).save(&path).unwrap(); path.display().to_string() }) .collect() @@ -70,11 +70,13 @@ fn create_imports_the_listed_maps_in_the_chosen_normal_format() { assert!(!state.ui.windows.new_project, "the dialog closes"); let project = &state.session.doc.project; assert_eq!(project.normal_format, NormalFormat::DirectX); - let baked = |ts: usize, map: BakedMap| state.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)); + let baked = |ts: usize, map: BakedMap| state.session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)); assert!(baked(0, BakedMap::Normal) && baked(1, BakedMap::AmbientOcclusion)); + let normal_green = state.session.doc.baked[&0].maps[&BakedMap::Normal][1]; + assert!(normal_green > 0.75, "the normal map is read as DirectX (green flipped): {normal_green}"); assert_eq!(state.session.doc.resources.len(), 2, "the file naming no map is not imported"); let toast = &state.toasts.last().unwrap().text; - assert!(toast.contains("Imported 2 baked maps") && toast.contains("Ball_notes.png"), "{toast}"); + assert!(toast.contains("Baked maps imported: 2") && toast.contains("Ball_notes.png"), "{toast}"); assert!(state.ui.new_project.baked_maps.is_empty(), "the next new project starts with no files"); assert_eq!(state.session.undo_label(), Some("Import baked maps")); } From bac53688c139d5779291c77d7ab7034613d729b2 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 12:13:03 +0000 Subject: [PATCH 39/73] Bake mode: draw the high poly, the cage and where the bake's rays miss The 3D view in bake mode gets a Baking Visualization panel (high poly, cage, UV seams, low poly, selected texture set only). The cage is built from the bake's own ray starts (a RayFrame now shared by the bake and the view), so it grows and shrinks with the distance sliders exactly as the rays do, and high-poly vertices the transfer rays cannot reach are drawn red. Refs #330 --- crates/bake/src/cage.rs | 15 + crates/bake/src/cage/cage_shell.rs | 65 +++ crates/bake/src/cage/high_poly_reach.rs | 103 +++++ crates/bake/src/cage/ray_frame.rs | 63 +++ crates/bake/src/cage/ray_start.rs | 20 + crates/bake/src/cage/vertex_reach.rs | 28 ++ crates/bake/src/lib.rs | 4 + crates/bake/src/map.rs | 3 + crates/bake/src/map/bake_context.rs | 86 +--- crates/bake/src/map/sampling.rs | 47 +- crates/bake/src/map/source.rs | 13 + crates/bake/src/map/transfer_keys.rs | 8 + crates/bake/src/mesh_extent.rs | 35 ++ crates/bake/src/test/cage_shell.rs | 103 +++++ crates/bake/src/test/high_poly_reach.rs | 198 ++++++++ crates/bake/src/tests.rs | 6 + crates/engine/src/bake/bake_cage_inputs.rs | 45 ++ crates/engine/src/bake/bake_meshes.rs | 5 + crates/engine/src/bake/mesh_map_command.rs | 90 +++- crates/engine/src/bake/mod.rs | 2 + crates/geom/src/mesh.rs | 54 +++ crates/render/src/bake_visualization.rs | 12 + crates/render/src/cage_gpu.rs | 9 + crates/render/src/high_poly_gpu.rs | 11 + crates/render/src/lib.rs | 5 + crates/render/src/renderer.rs | 423 ++++++++++++++---- crates/render/src/shaders/bake_view.wgsl | 88 ++++ crates/render/src/uv_seam_gpu.rs | 8 + crates/render/tests/headless.rs | 75 +++- .../src/bake_mode/bake_visualization_panel.rs | 61 +++ .../bake_mode/bake_visualization_toggles.rs | 34 ++ crates/ui-egui/src/bake_mode/mod.rs | 4 + crates/ui-egui/src/bake_scene.rs | 11 + .../ui-egui/src/bake_scene/bake_scene_link.rs | 213 +++++++++ crates/ui-egui/src/bake_scene/cage_link.rs | 16 + .../ui-egui/src/bake_scene/cage_shell_key.rs | 47 ++ crates/ui-egui/src/bake_scene/cage_upload.rs | 10 + crates/ui-egui/src/bake_scene/reach_link.rs | 100 +++++ .../ui-egui/src/bake_scene/shared_handle.rs | 32 ++ crates/ui-egui/src/gpu.rs | 206 ++++++--- crates/ui-egui/src/i18n/ar.rs | 5 + crates/ui-egui/src/i18n/de.rs | 5 + crates/ui-egui/src/i18n/es.rs | 5 + crates/ui-egui/src/i18n/fr.rs | 5 + crates/ui-egui/src/i18n/it.rs | 5 + crates/ui-egui/src/i18n/ja.rs | 5 + crates/ui-egui/src/i18n/ko.rs | 5 + crates/ui-egui/src/i18n/pt_br.rs | 5 + crates/ui-egui/src/i18n/zh_hans.rs | 5 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/viewport.rs | 56 ++- 52 files changed, 2179 insertions(+), 285 deletions(-) create mode 100644 crates/bake/src/cage.rs create mode 100644 crates/bake/src/cage/cage_shell.rs create mode 100644 crates/bake/src/cage/high_poly_reach.rs create mode 100644 crates/bake/src/cage/ray_frame.rs create mode 100644 crates/bake/src/cage/ray_start.rs create mode 100644 crates/bake/src/cage/vertex_reach.rs create mode 100644 crates/bake/src/map/transfer_keys.rs create mode 100644 crates/bake/src/mesh_extent.rs create mode 100644 crates/bake/src/test/cage_shell.rs create mode 100644 crates/bake/src/test/high_poly_reach.rs create mode 100644 crates/engine/src/bake/bake_cage_inputs.rs create mode 100644 crates/render/src/bake_visualization.rs create mode 100644 crates/render/src/cage_gpu.rs create mode 100644 crates/render/src/high_poly_gpu.rs create mode 100644 crates/render/src/shaders/bake_view.wgsl create mode 100644 crates/render/src/uv_seam_gpu.rs create mode 100644 crates/ui-egui/src/bake_mode/bake_visualization_panel.rs create mode 100644 crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs create mode 100644 crates/ui-egui/src/bake_scene.rs create mode 100644 crates/ui-egui/src/bake_scene/bake_scene_link.rs create mode 100644 crates/ui-egui/src/bake_scene/cage_link.rs create mode 100644 crates/ui-egui/src/bake_scene/cage_shell_key.rs create mode 100644 crates/ui-egui/src/bake_scene/cage_upload.rs create mode 100644 crates/ui-egui/src/bake_scene/reach_link.rs create mode 100644 crates/ui-egui/src/bake_scene/shared_handle.rs diff --git a/crates/bake/src/cage.rs b/crates/bake/src/cage.rs new file mode 100644 index 00000000..d2c7d7f3 --- /dev/null +++ b/crates/bake/src/cage.rs @@ -0,0 +1,15 @@ +//! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws + +mod cage_shell; +mod high_poly_reach; +mod ray_frame; +mod ray_start; +mod vertex_reach; + +#[cfg(test)] +pub(crate) use cage_shell::CORNERS; +pub use cage_shell::CageShell; +pub use high_poly_reach::HighPolyReach; +pub(crate) use ray_frame::RayFrame; +pub use ray_start::RayStart; +pub use vertex_reach::VertexReach; diff --git a/crates/bake/src/cage/cage_shell.rs b/crates/bake/src/cage/cage_shell.rs new file mode 100644 index 00000000..e1664219 --- /dev/null +++ b/crates/bake/src/cage/cage_shell.rs @@ -0,0 +1,65 @@ +use super::{RayFrame, RayStart}; +use crate::{BakeError, BakeRequest, MeshExtent}; +use rayon::prelude::*; +use std::collections::{HashMap, HashSet}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::surface_at; + +/// Barycentric coordinates of a triangle's three corners +pub(crate) const CORNERS: [[f32; 2]; 3] = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]; + +/// The cage of one texture set as the bake sees it: where its transfer rays start at each corner of the set's triangles +#[derive(Clone, Debug, Default)] +pub struct CageShell { + /// Low-poly position of each triangle corner, three per triangle + pub positions: Vec, + pub starts: Vec, + /// Corner pairs along the low poly's polygon edges, for the wireframe + pub edges: Vec<[u32; 2]>, + /// World units per unit of the max frontal distance setting + pub cage_units: f32, +} + +impl CageShell { + /// The cage of `request`'s texture set, from the same ray starts the bake uses + pub fn new(request: &BakeRequest) -> Result { + let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?; + let (frame, mesh) = (&ray_frame, request.mesh); + let triangles: Vec = mesh.triangles_of(request.material).collect(); + let (positions, starts): (Vec, Vec) = triangles + .par_iter() + .flat_map_iter(|&triangle| { + CORNERS.into_iter().map(move |barycentric| match surface_at(mesh, triangle as u32, barycentric[0], barycentric[1]) { + Some(surface) => (surface.pos, frame.start(&surface, barycentric)), + None => (Vec3::ZERO, RayStart::Distance { up: Vec3::ZERO, scale: 0.0 }), + }) + }) + .unzip(); + + let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect(); + let mut edge_corners = HashMap::new(); + for (triangle_index, &triangle) in triangles.iter().enumerate() { + let Some(vertices) = mesh.tri(triangle) else { continue }; + + for corner in 0..3 { + let next = (corner + 1) % 3; + let (from, to) = (vertices[corner] as u32, vertices[next] as u32); + let key = (from.min(to), from.max(to)); + if wire_edges.contains(&key) { + let first_corner = (triangle_index * 3) as u32; + edge_corners.entry(key).or_insert([first_corner + corner as u32, first_corner + next as u32]); + } + } + } + let mut edges: Vec<[u32; 2]> = edge_corners.into_values().collect(); + edges.sort_unstable(); + + Ok(CageShell { positions, starts, edges, cage_units: ray_frame.cage_units }) + } + + /// Each corner's cage position at `max_frontal`, the setting before relative-to-bounding-box scaling + pub fn corners(&self, max_frontal: f32) -> Vec { + let frontal = max_frontal * self.cage_units; + self.positions.par_iter().zip(&self.starts).map(|(position, start)| start.origin(*position, frontal)).collect() + } +} diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs new file mode 100644 index 00000000..f957ce49 --- /dev/null +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -0,0 +1,103 @@ +use super::{RayFrame, VertexReach}; +use crate::map::transfer_keys; +use crate::tracing::ANY; +use crate::{BakeError, BakeRequest, MeshExtent}; +use rayon::prelude::*; +use texturecraft_core::MeshMatchMode; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, surface_at}; + +/// Where each high-poly vertex sits relative to the transfer rays of one texture set, to show which parts its bake misses +#[derive(Clone, Debug, Default)] +pub struct HighPolyReach { + /// Per high-poly vertex; `None` where another texture set's low poly is nearer or the request has no high poly + pub vertices: Vec>, + /// World units per unit of the cage distance settings + pub cage_units: f32, + pub ignore_backface: bool, +} + +impl HighPolyReach { + /// The reach of `request`'s transfer rays at the high-poly vertices whose nearest low-poly point is on this set, from the same ray starts the bake uses there + pub fn new(request: &BakeRequest) -> Result { + let Some(high) = request.high else { return Ok(HighPolyReach::default()) }; + + let frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?; + let mut in_set = vec![false; request.mesh.triangle_count()]; + for triangle in request.mesh.triangles_of(request.material) { + if let Some(flag) = in_set.get_mut(triangle) { + *flag = true; + } + } + + let winding_normals = winding_normals(high.mesh); + let (low_keys, high_vertex_keys) = match request.settings.high_poly.match_mode { + MeshMatchMode::Always => (Vec::new(), Vec::new()), + MeshMatchMode::ByMeshName => { + let (low_keys, high_keys) = transfer_keys(request); + (low_keys, vertex_keys(high.mesh, &high_keys)) + } + }; + let key = |keys: &[u32], index: usize| keys.get(index).copied().unwrap_or(ANY); + let frame = &frame; + let vertices = high + .mesh + .positions + .par_iter() + .zip(&winding_normals) + .enumerate() + .map(|(vertex, (&high_position, &high_facing))| { + let nearest = request.bvh.nearest(high_position, f32::INFINITY, &|_| true)?; + if !in_set.get(nearest.tri as usize).copied().unwrap_or(false) { + return None; + } + + let surface = surface_at(request.mesh, nearest.tri, nearest.u, nearest.v)?; + let ray_key = key(&low_keys, nearest.tri as usize); + Some(VertexReach { + low_position: surface.pos, + start: frame.start(&surface, [nearest.u, nearest.v]), + high_position, + high_facing, + name_matches: ray_key == ANY || key(&high_vertex_keys, vertex) == ray_key, + }) + }) + .collect(); + + Ok(HighPolyReach { vertices, cage_units: frame.cage_units, ignore_backface: request.settings.high_poly.ignore_backface }) + } + + /// Whether the transfer rays miss high-poly vertex `vertex` at the `max_frontal` and `max_rear` settings; `None` when the vertex isn't this set's + pub fn missed(&self, vertex: usize, max_frontal: f32, max_rear: f32) -> Option { + let reach = self.vertices.get(vertex).copied().flatten()?; + Some(reach.missed(max_frontal * self.cage_units, max_rear * self.cage_units, self.ignore_backface)) + } +} + +/// Each vertex's mesh-name key, from the first triangle that uses it +fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { + let mut keys = vec![ANY; mesh.positions.len()]; + for (corners, &triangle_key) in mesh.indices.chunks_exact(3).zip(triangle_keys) { + for &corner in corners { + if let Some(key) = keys.get_mut(corner as usize).filter(|key| **key == ANY) { + *key = triangle_key; + } + } + } + keys +} + +/// Each vertex's sum of its triangles' winding normals, weighted by area: the side the bake's backface test sees as the front +fn winding_normals(mesh: &Mesh) -> Vec { + let mut normals = vec![Vec3::ZERO; mesh.positions.len()]; + for corners in mesh.indices.chunks_exact(3) { + let position = |corner: u32| mesh.positions.get(corner as usize).copied().unwrap_or(Vec3::ZERO); + let winding_normal = (position(corners[1]) - position(corners[0])).cross(position(corners[2]) - position(corners[0])); + for &corner in corners { + if let Some(normal) = normals.get_mut(corner as usize) { + *normal += winding_normal; + } + } + } + normals +} diff --git a/crates/bake/src/cage/ray_frame.rs b/crates/bake/src/cage/ray_frame.rs new file mode 100644 index 00000000..e8692cf2 --- /dev/null +++ b/crates/bake/src/cage/ray_frame.rs @@ -0,0 +1,63 @@ +use super::RayStart; +use crate::MeshExtent; +use crate::map::{interpolate, welded}; +use crate::skew::PreparedSkew; +use crate::{BakeError, BakePaintMap, BakeRequest}; +use texturecraft_core::CageType; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, Surface}; + +/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount +pub(crate) struct RayFrame<'a> { + mesh: &'a Mesh, + ray_normals: Vec, + cage: Option<&'a Mesh>, + skew: Option>, + cage_paint: Option<&'a BakePaintMap>, + /// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead + ray_epsilon: f32, + /// World units per unit of the cage distance settings + pub(crate) cage_units: f32, +} + +impl<'a> RayFrame<'a> { + pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result, BakeError> { + let settings = request.settings; + let ray_normals = match settings.cage.average_normals && request.high.is_some() { + true => { + let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal); + welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() + } + false => Vec::new(), + }; + + Ok(RayFrame { + mesh: request.mesh, + ray_normals, + cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, + skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?, + cage_paint: request.cage_paint, + ray_epsilon: extent.ray_epsilon(), + cage_units: if settings.cage.relative_to_bounding_box { extent.scale } else { 1.0 }, + }) + } + + /// Where the transfer ray of the low-poly point `surface` at `barycentric` starts + pub(crate) fn start(&self, surface: &Surface, barycentric: [f32; 2]) -> RayStart { + let cage_offset = self + .cage + .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric)) + .map(|cage_position| surface.pos - cage_position) + .filter(|offset| offset.length() > self.ray_epsilon); + if let Some(offset) = cage_offset { + return RayStart::CageMesh(offset); + } + + let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let up = match &self.skew { + Some(skew) => skew.correct(self.mesh, surface, averaged_normal), + None => averaged_normal, + }; + RayStart::Distance { up, scale: self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)) } + } +} diff --git a/crates/bake/src/cage/ray_start.rs b/crates/bake/src/cage/ray_start.rs new file mode 100644 index 00000000..c0c3923a --- /dev/null +++ b/crates/bake/src/cage/ray_start.rs @@ -0,0 +1,20 @@ +use texturecraft_geom::glam::Vec3; + +/// Where the bake's transfer ray for one low-poly point starts +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum RayStart { + /// On the cage mesh: the offset from the cage to the low-poly point + CageMesh(Vec3), + /// Out along `up` by the frontal distance times `scale` (the painted cage amount) + Distance { up: Vec3, scale: f32 }, +} + +impl RayStart { + /// The ray origin for the low-poly point `position` at `frontal` world units of max frontal distance + pub fn origin(&self, position: Vec3, frontal: f32) -> Vec3 { + match *self { + RayStart::CageMesh(offset) => position - offset, + RayStart::Distance { up, scale } => position + up * frontal * scale, + } + } +} diff --git a/crates/bake/src/cage/vertex_reach.rs b/crates/bake/src/cage/vertex_reach.rs new file mode 100644 index 00000000..34adea92 --- /dev/null +++ b/crates/bake/src/cage/vertex_reach.rs @@ -0,0 +1,28 @@ +use super::RayStart; +use texturecraft_geom::glam::Vec3; + +/// One high-poly vertex seen from the transfer ray through its nearest low-poly point +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct VertexReach { + pub low_position: Vec3, + pub start: RayStart, + pub high_position: Vec3, + /// The side the high poly's triangles face at the vertex, by their winding (not normalized) + pub high_facing: Vec3, + /// Whether the bake lets this low-poly point's ray hit the vertex's part (always, unless matching by mesh name) + pub name_matches: bool, +} + +impl VertexReach { + /// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray + pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool { + let origin = self.start.origin(self.low_position, frontal); + let (direction, front) = match self.start { + RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()), + RayStart::Distance { up, scale } => (-up, frontal * scale), + }; + let along_ray = (self.high_position - origin).dot(direction); + + !self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0) + } +} diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index a8b087bc..eb8a61de 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -6,13 +6,17 @@ mod bake_error; mod bake_output; mod bake_request; +mod cage; mod high_poly; +mod mesh_extent; mod progress; pub use bake_error::BakeError; pub use bake_output::BakeOutput; pub use bake_request::BakeRequest; +pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach}; pub use high_poly::HighPoly; +pub(crate) use mesh_extent::MeshExtent; pub use progress::Progress; mod map; diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs index 384d9d02..c9c30fd6 100644 --- a/crates/bake/src/map.rs +++ b/crates/bake/src/map.rs @@ -15,10 +15,13 @@ mod source; mod texel_grid; mod traced; mod transfer; +mod transfer_keys; pub(crate) use bake_context::BakeContext; pub(crate) use normal_curvature::curvature_from_normal; pub(crate) use sample::Sample; +pub(crate) use sampling::{interpolate, welded}; pub(crate) use texel_grid::TexelGrid; pub(crate) use traced::Traced; pub(crate) use transfer::Transfer; +pub(crate) use transfer_keys::transfer_keys; diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs index 21fed094..f3e35df6 100644 --- a/crates/bake/src/map/bake_context.rs +++ b/crates/bake/src/map/bake_context.rs @@ -1,28 +1,22 @@ use super::curvature::Curvature; -use super::sampling::{interpolate, pack, splitmix64, tangent_normal, welded}; +use super::sampling::{pack, splitmix64, tangent_normal}; use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer}; -use crate::skew::PreparedSkew; +use crate::cage::{RayFrame, RayStart}; use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; -use crate::{BakeError, BakeRequest}; +use crate::{BakeError, BakeRequest, MeshExtent}; use rayon::prelude::*; -use std::collections::HashMap; use texturecraft_core::{ - AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CageType, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion, + AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion, }; -use texturecraft_geom::glam::Vec3; -use texturecraft_geom::{Hit, Mesh, Surface, surface_at}; +use texturecraft_geom::{Hit, Surface, surface_at}; const CURVATURE_CHUNK: usize = 1 << 15; pub(crate) struct BakeContext<'a> { low: Source<'a>, high: Option>, - cage: Option<&'a Mesh>, - skew: Option>, - cage_paint: Option<&'a crate::BakePaintMap>, - ray_normals: Vec, + ray_frame: RayFrame<'a>, settings: &'a BakeSettings, - eps: f32, frontal: f32, rear: f32, position: PositionProjection, @@ -36,36 +30,10 @@ pub(crate) struct BakeContext<'a> { impl<'a> BakeContext<'a> { pub(crate) fn new(request: &BakeRequest<'a>) -> Result, BakeError> { let settings = request.settings; - let (bounds_min, bounds_max) = request.mesh.bounds(); - let mesh_diagonal = (bounds_max - bounds_min).length().max(1e-6); - if !mesh_diagonal.is_finite() { - return Err(BakeError::Invalid("mesh bounds are too large".into())); - } - - let mesh_scale = (bounds_max - bounds_min).max_element().max(1e-6); - let mut name_keys = HashMap::new(); - let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.high_poly.low_suffix, &settings.high_poly, &mut name_keys); - let high = request.high.map(|high_mesh| { - Source::new( - high_mesh.mesh, - high_mesh.bvh, - high_mesh.base_color, - high_mesh.file_ids, - &settings.high_poly.high_suffix, - &settings.high_poly, - &mut name_keys, - ) - }); - let ray_normals = match settings.cage.average_normals && high.is_some() { - true => { - let (welded_indices, _, normals) = welded(request.mesh, mesh_diagonal); - welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() - } - false => Vec::new(), - }; - - let skew = request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, mesh_scale, settings.skew)).transpose()?; - let ray_epsilon = 1e-6 * mesh_diagonal; + let extent = MeshExtent::of(request.mesh)?; + let (low, high) = Source::of_request(request); + let ray_frame = RayFrame::new(request, extent)?; + let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon()); let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| { let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians(); let units = if ray_settings.relative_to_bounding_box { mesh_scale } else { 1.0 }; @@ -91,27 +59,26 @@ impl<'a> BakeContext<'a> { pass.ignore_backface = parameters.ignore_backface; pass.same_key = parameters.self_occlusion == SelfOcclusion::SameMeshName; pass.attenuation = parameters.attenuation; - pass.ground_height = parameters.ground_plane.enabled.then_some(bounds_min.y - parameters.ground_plane.offset); + pass.ground_height = parameters.ground_plane.enabled.then_some(extent.bounds_min.y - parameters.ground_plane.offset); } + let mut bent = pass(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays, RayKind::Occlusion); if let Some(pass) = &mut bent { pass.ignore_backface = settings.maps.bent_normal.parameters.ignore_backface; pass.same_key = settings.maps.bent_normal.parameters.self_occlusion == SelfOcclusion::SameMeshName; } + let mut thickness = pass(BakedMap::Thickness, &settings.maps.thickness.parameters.rays, RayKind::Thickness); if let Some(pass) = &mut thickness { pass.same_key = settings.maps.thickness.parameters.self_occlusion == SelfOcclusion::SameMeshName; } - let cage_units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 }; + + let cage_units = ray_frame.cage_units; Ok(BakeContext { low, high, - cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, - skew, - cage_paint: request.cage_paint, - ray_normals, + ray_frame, settings, - eps: ray_epsilon, frontal: settings.cage.max_frontal * cage_units, rear: settings.cage.max_rear * cage_units, position: PositionProjection::new(request.mesh, request.material, settings.maps.position.parameters), @@ -140,22 +107,11 @@ impl<'a> BakeContext<'a> { } pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) { - let averaged_normal = interpolate(self.low.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); - let cage = self - .cage - .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric)) - .map(|cage_position| surface.pos - cage_position) - .filter(|offset| offset.length() > self.eps); - let cage_scale = self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)); - let (origin, direction, front) = match cage { - Some(offset) => (surface.pos - offset, offset.normalize(), offset.length()), - None => { - let up = match &self.skew { - Some(skew) => skew.correct(self.low.mesh, surface, averaged_normal), - None => averaged_normal, - }; - (surface.pos + up * self.frontal * cage_scale, -up, self.frontal * cage_scale) - } + let start = self.ray_frame.start(surface, barycentric); + let origin = start.origin(surface.pos, self.frontal); + let (direction, front) = match start { + RayStart::CageMesh(offset) => (offset.normalize(), offset.length()), + RayStart::Distance { up, scale } => (-up, self.frontal * scale), }; let key = match self.settings.high_poly.match_mode { MeshMatchMode::Always => ANY, diff --git a/crates/bake/src/map/sampling.rs b/crates/bake/src/map/sampling.rs index d19e4afa..5f2d2677 100644 --- a/crates/bake/src/map/sampling.rs +++ b/crates/bake/src/map/sampling.rs @@ -3,34 +3,43 @@ use std::ops::{Add, Mul}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, Surface}; -pub(super) fn interpolate + Add>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option { - let [a, b, c] = mesh.tri(tri as usize)?; - Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2) +/// `values` (one per vertex) at `barycentric` in triangle `triangle` +pub(crate) fn interpolate + Add>(mesh: &Mesh, values: &[T], triangle: u32, barycentric: [f32; 2]) -> Option { + let [first, second, third] = mesh.tri(triangle as usize)?; + let [second_weight, third_weight] = barycentric; + + Some(*values.get(first)? * (1.0 - second_weight - third_weight) + *values.get(second)? * second_weight + *values.get(third)? * third_weight) } -pub(super) fn welded(mesh: &Mesh, diag: f32) -> (Vec, Vec, Vec) { - let q = diag * 1e-5; - let mut ids: HashMap<[i64; 3], u32> = HashMap::new(); - let (mut pos, mut nrm) = (Vec::new(), Vec::::new()); - let weld: Vec = mesh +/// Vertices closer than this fraction of the mesh diagonal count as one when welding +const WELD_TOLERANCE_PER_DIAGONAL: f32 = 1e-5; + +/// Vertices that share a position merged: each vertex's welded index, the welded positions and their averaged normals +pub(crate) fn welded(mesh: &Mesh, diagonal: f32) -> (Vec, Vec, Vec) { + let tolerance = diagonal * WELD_TOLERANCE_PER_DIAGONAL; + let mut welded_index_of_cell: HashMap<[i64; 3], u32> = HashMap::new(); + let (mut positions, mut normal_sums) = (Vec::new(), Vec::::new()); + + let welded_indices: Vec = mesh .positions .iter() .zip(&mesh.normals) - .map(|(p, n)| { - let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64); - let id = *ids.entry(key).or_insert_with(|| { - pos.push(*p); - nrm.push(Vec3::ZERO); - (pos.len() - 1) as u32 + .map(|(position, normal)| { + let cell = [position.x, position.y, position.z].map(|coordinate| (coordinate / tolerance).round() as i64); + let welded_index = *welded_index_of_cell.entry(cell).or_insert_with(|| { + positions.push(*position); + normal_sums.push(Vec3::ZERO); + (positions.len() - 1) as u32 }); - if let Some(acc) = nrm.get_mut(id as usize) { - *acc += *n; + if let Some(normal_sum) = normal_sums.get_mut(welded_index as usize) { + *normal_sum += *normal; } - id + welded_index }) .collect(); - let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect(); - (weld, pos, nrm) + + let normals = normal_sums.into_iter().map(|normal_sum| normal_sum.try_normalize().unwrap_or(Vec3::ZERO)).collect(); + (welded_indices, positions, normals) } pub(super) fn splitmix64(x: u64) -> u64 { diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs index 0e1f9164..ad057b11 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -1,4 +1,5 @@ use super::sampling::{generated_hue, interpolate, splitmix64}; +use crate::BakeRequest; use crate::tracing::{ANY, TraceMesh}; use std::collections::HashMap; use std::sync::Arc; @@ -21,6 +22,18 @@ pub(super) struct Source<'a> { } impl<'a> Source<'a> { + /// `request`'s low and high poly, their mesh names keyed from one shared table so the bake can match a low-poly part to its high-poly part + pub(super) fn of_request(request: &BakeRequest<'a>) -> (Source<'a>, Option>) { + let settings = &request.settings.high_poly; + let mut name_keys = HashMap::new(); + let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.low_suffix, settings, &mut name_keys); + let high = request.high.map(|high_mesh| { + Source::new(high_mesh.mesh, high_mesh.bvh, high_mesh.base_color, high_mesh.file_ids, &settings.high_suffix, settings, &mut name_keys) + }); + + (low, high) + } + pub(super) fn new( mesh: &'a Mesh, bvh: &'a Bvh, diff --git a/crates/bake/src/map/transfer_keys.rs b/crates/bake/src/map/transfer_keys.rs new file mode 100644 index 00000000..69e9b12a --- /dev/null +++ b/crates/bake/src/map/transfer_keys.rs @@ -0,0 +1,8 @@ +use super::source::Source; +use crate::BakeRequest; + +/// The bake's mesh-name key of each low-poly and each high-poly triangle: with By Mesh Name a transfer ray from a low-poly triangle only hits high-poly triangles with its key +pub(crate) fn transfer_keys(request: &BakeRequest) -> (Vec, Vec) { + let (low, high) = Source::of_request(request); + (low.key, high.map(|high| high.key).unwrap_or_default()) +} diff --git a/crates/bake/src/mesh_extent.rs b/crates/bake/src/mesh_extent.rs new file mode 100644 index 00000000..3c6fa48d --- /dev/null +++ b/crates/bake/src/mesh_extent.rs @@ -0,0 +1,35 @@ +use crate::BakeError; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::Vec3; + +/// Smallest size a mesh is treated as having, so a flat or empty mesh still gives finite distances +const MIN_MESH_SIZE: f32 = 1e-6; + +/// How far a ray starts past the surface it leaves, as a fraction of the mesh diagonal +const RAY_EPSILON_PER_DIAGONAL: f32 = 1e-6; + +/// The low-poly mesh's size, which scales the bake's relative distances +#[derive(Clone, Copy, Debug)] +pub(crate) struct MeshExtent { + pub(crate) bounds_min: Vec3, + pub(crate) diagonal: f32, + /// The bounding box's largest side + pub(crate) scale: f32, +} + +impl MeshExtent { + pub(crate) fn of(mesh: &Mesh) -> Result { + let (bounds_min, bounds_max) = mesh.bounds(); + let diagonal = (bounds_max - bounds_min).length().max(MIN_MESH_SIZE); + if !diagonal.is_finite() { + return Err(BakeError::Invalid("mesh bounds are too large".into())); + } + + Ok(MeshExtent { bounds_min, diagonal, scale: (bounds_max - bounds_min).max_element().max(MIN_MESH_SIZE) }) + } + + /// How far a ray starts past the surface it leaves, in world units + pub(crate) fn ray_epsilon(&self) -> f32 { + RAY_EPSILON_PER_DIAGONAL * self.diagonal + } +} diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs new file mode 100644 index 00000000..2d114b06 --- /dev/null +++ b/crates/bake/src/test/cage_shell.rs @@ -0,0 +1,103 @@ +use super::settings; +use crate::cage::CORNERS; +use crate::map::BakeContext; +use crate::{BakePaintMap, BakeRequest, CageShell, HighPoly}; +use texturecraft_core::{BakedMap, CageType}; +use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::{Bvh, Mesh, primitives, surface_at}; + +/// A painted map whose values vary over the UV square +fn painted_map() -> BakePaintMap { + let mut map = BakePaintMap::constant(0.25).resized(32, 32).unwrap(); + map.paint(&[Vec2::new(0.2, 0.3), Vec2::new(0.7, 0.6)], 0.3, 1.0, 0.5, 1.0).unwrap(); + map +} + +/// Every corner of `request`'s cage equals the origin of the bake's transfer ray at that corner, bit for bit +fn assert_cage_matches_the_ray_origins(request: &BakeRequest) { + let shell = CageShell::new(request).unwrap(); + let corners = shell.corners(request.settings.cage.max_frontal); + let context = BakeContext::new(request).unwrap(); + let triangles: Vec = request.mesh.triangles_of(request.material).collect(); + assert_eq!(corners.len(), triangles.len() * 3); + + for (corner_index, corner) in corners.iter().enumerate() { + let barycentric = CORNERS[corner_index % 3]; + let surface = surface_at(request.mesh, triangles[corner_index / 3] as u32, barycentric[0], barycentric[1]).unwrap(); + let (ray, _) = context.transfer_ray(&surface, barycentric); + assert_eq!(*corner, ray.origin, "corner {corner_index}"); + } +} + +#[test] +fn the_cage_corners_are_the_bake_ray_origins() { + let low = primitives::cube(1.0); + let high_mesh = primitives::sphere(0.8, 16, 8); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }; + let (skew, cage_paint) = (painted_map(), painted_map()); + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.max_frontal = 0.03; + bake_settings.skew.edge_protection = true; + let request = |settings| BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings, + high: Some(high), + cage: None, + skew: Some(&skew), + cage_paint: Some(&cage_paint), + tiles: (1, 1), + }; + + assert_cage_matches_the_ray_origins(&request(&bake_settings)); + let face_normals = { + let mut face_normals = bake_settings.clone(); + face_normals.cage.average_normals = false; + face_normals.cage.relative_to_bounding_box = false; + face_normals + }; + assert_cage_matches_the_ray_origins(&request(&face_normals)); +} + +#[test] +fn the_cage_follows_the_frontal_distance_and_a_cage_mesh() { + let low = primitives::cube(1.0); + let low_bvh = Bvh::new(&low); + let high = HighPoly { file_ids: &[], mesh: &low, bvh: &low_bvh, base_color: &[] }; + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(high), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let shell = CageShell::new(&request).unwrap(); + let distance_from_the_cube = |max_frontal: f32| shell.corners(max_frontal).iter().map(|corner| corner.abs().max_element() - 0.5).fold(0.0, f32::max); + + assert!(distance_from_the_cube(0.0).abs() < 1e-6, "at frontal 0 the cage is the low poly"); + // Averaged normals point diagonally at the corners, so a corner moves out by at least half the distance along each axis + assert!(distance_from_the_cube(0.2) > 0.1 && distance_from_the_cube(0.2) <= 0.2 + 1e-6, "the cage grows with the frontal distance"); + assert_eq!(shell.edges.len(), low.wire_edges()[0].len(), "one wireframe line per polygon edge"); + + let cage_mesh = Mesh { positions: low.positions.iter().map(|position| *position * 1.5).collect(), ..low.clone() }; + let custom_settings = { + let mut custom_settings = bake_settings.clone(); + custom_settings.cage.kind = CageType::CustomFile; + custom_settings + }; + let custom = BakeRequest { settings: &custom_settings, cage: Some(&cage_mesh), ..request }; + assert_cage_matches_the_ray_origins(&custom); + let corners = CageShell::new(&custom).unwrap().corners(0.0); + assert!(corners.iter().all(|corner| (corner.abs().max_element() - 0.75).abs() < 1e-6), "the cage mesh is drawn as it is"); + assert!(corners.iter().all(|corner| corner.is_finite() && *corner != Vec3::ZERO)); +} diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs new file mode 100644 index 00000000..bb8753f8 --- /dev/null +++ b/crates/bake/src/test/high_poly_reach.rs @@ -0,0 +1,198 @@ +use super::settings; +use crate::map::{BakeContext, transfer_keys}; +use crate::tracing::ANY; +use crate::{BakeRequest, HighPoly, HighPolyReach, RayStart}; +use texturecraft_core::{BakedMap, MeshMatchMode}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Bvh, Mesh, primitives, surface_at}; + +/// Ray distances closer than this to the end of the ray's range are left out: rounding decides them +const BOUNDARY: f32 = 1e-4; + +/// How close the ray's hit must be to the vertex to count as reaching it +const HIT_TOLERANCE: f32 = 1e-4; + +/// A bumpy plane over the flat low poly, with the triangles right of `FLIPPED_FROM_X` wound the other way +fn bumpy_high_poly() -> (Mesh, Vec) { + const FLIPPED_FROM_X: f32 = 0.2; + + let mut mesh = primitives::plane(1.0, 40); + for position in &mut mesh.positions { + position.y = 0.04 * (position.x * 9.0).sin() * (position.z * 7.0).cos() + 0.005; + } + + let mut flipped = vec![false; mesh.positions.len()]; + let mut unflipped = vec![false; mesh.positions.len()]; + for corners in mesh.indices.chunks_exact_mut(3) { + let center_x = corners.iter().map(|&corner| mesh.positions[corner as usize].x).sum::() / 3.0; + if center_x > FLIPPED_FROM_X { + corners.swap(1, 2); + } + for &corner in corners.iter() { + if center_x > FLIPPED_FROM_X { flipped[corner as usize] = true } else { unflipped[corner as usize] = true } + } + } + // Vertices on the border face both ways: neither answer is right for them + let mixed = flipped.iter().zip(&unflipped).map(|(flipped, unflipped)| *flipped && *unflipped).collect(); + (mesh, mixed) +} + +#[test] +fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() { + let low = primitives::plane(1.0, 8); + let (high_mesh, mixed) = bumpy_high_poly(); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }; + let back_facing = |triangle: u32, direction: Vec3| { + let [a, b, c] = high_mesh.tri(triangle as usize).unwrap().map(|corner| high_mesh.positions[corner]); + (b - a).cross(c - a).dot(direction) > 0.0 + }; + let mut checked = [0usize; 2]; + + for ignore_backface in [false, true] { + for (max_frontal, max_rear) in [(0.0, 0.01), (0.02, 0.0), (0.02, 0.01), (0.05, 0.05)] { + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + bake_settings.high_poly.ignore_backface = ignore_backface; + (bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (max_frontal, max_rear); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(high), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + let context = BakeContext::new(&request).unwrap(); + + for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { + let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap()); + let RayStart::Distance { scale, .. } = vertex_reach.start else { panic!("a distance-based cage") }; + let height = vertex_reach.high_position.y - vertex_reach.low_position.y; + let near_the_range_end = [max_frontal * scale, -max_rear].iter().any(|end| (height - end).abs() < BOUNDARY); + if near_the_range_end || mixed[vertex] { + continue; + } + + let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap(); + let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap(); + let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]); + let hit = high_bvh + .closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| !(ignore_backface && back_facing(triangle, ray.direction))); + let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE); + assert_eq!( + missed, !reaches_the_vertex, + "vertex {vertex}, ignore backface {ignore_backface}, frontal {max_frontal}, rear {max_rear}: height {height}" + ); + checked[usize::from(missed)] += 1; + } + } + } + assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}"); +} + +#[test] +fn a_vertex_belongs_to_the_texture_set_whose_low_poly_is_nearest() { + let mut low = primitives::plane(1.0, 4); + let mut right = primitives::plane(1.0, 4); + for position in &mut right.positions { + position.x += 2.0; + } + low.append(&right); + assert_eq!(low.materials.len(), 2, "each plane is its own texture set"); + let mut high_mesh = primitives::plane(3.0, 30); + for position in &mut high_mesh.positions { + position.x += 1.0; + position.y = 0.3; + } + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let bake_settings = settings(16, &[BakedMap::Normal]); + let request = |material| BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let (left, right) = (HighPolyReach::new(&request(0)).unwrap(), HighPolyReach::new(&request(1)).unwrap()); + + for (vertex, position) in high_mesh.positions.iter().enumerate() { + let owners = (left.vertices[vertex].is_some(), right.vertices[vertex].is_some()); + assert!(owners != (true, true), "vertex {vertex} belongs to one set at most"); + if position.x < 0.9 { + assert_eq!(owners, (true, false), "vertex {vertex} at {position} is over the left set"); + } else if position.x > 1.1 { + assert_eq!(owners, (false, true), "vertex {vertex} at {position} is over the right set"); + } + } +} + +#[test] +fn matching_by_mesh_name_misses_the_parts_with_another_name() { + const HEIGHT_INSIDE_THE_CAGE: f32 = 0.01; + + let mut low = primitives::plane(1.0, 8); + low.submeshes[0].name = "part_low".into(); + let mut high_mesh = primitives::plane(0.5, 10); + let mut other_part = primitives::plane(0.5, 10); + for (mesh, center_x) in [(&mut high_mesh, -0.25), (&mut other_part, 0.25)] { + for position in &mut mesh.positions { + position.x += center_x; + position.y = HEIGHT_INSIDE_THE_CAGE; + } + } + high_mesh.append(&other_part); + high_mesh.submeshes[0].name = "part_high".into(); + high_mesh.submeshes[1].name = "other_high".into(); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + bake_settings.cage.max_frontal = 0.02; + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + let context = BakeContext::new(&request).unwrap(); + let (_, high_keys) = transfer_keys(&request); + + for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { + let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap()); + // On the line where the two parts meet, a ray reaches either part's triangles + if vertex_reach.high_position.x.abs() < BOUNDARY { + continue; + } + + let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap(); + let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap(); + let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]); + let same_name = |triangle: u32| ray.key == ANY || high_keys.get(triangle as usize) == Some(&ray.key); + let hit = high_bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &same_name); + let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE); + assert_eq!(missed, !reaches_the_vertex, "vertex {vertex} at {}", vertex_reach.high_position); + assert_eq!( + missed, + vertex >= high_mesh.positions.len() - other_part.positions.len(), + "only the part named like the low poly is reached: vertex {vertex}" + ); + } +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 26c8665c..c834da7a 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -14,6 +14,12 @@ use texturecraft_geom::primitives; use super::*; +#[path = "test/cage_shell.rs"] +mod cage_shell; + +#[path = "test/high_poly_reach.rs"] +mod high_poly_reach; + #[path = "test/setting.rs"] mod setting; diff --git a/crates/engine/src/bake/bake_cage_inputs.rs b/crates/engine/src/bake/bake_cage_inputs.rs new file mode 100644 index 00000000..ab559beb --- /dev/null +++ b/crates/engine/src/bake/bake_cage_inputs.rs @@ -0,0 +1,45 @@ +use super::MergedHigh; +use std::sync::Arc; +use texturecraft_bake::{BakeError, BakePaintMap, BakeRequest, CageShell, HighPoly, HighPolyReach}; +use texturecraft_core::BakeSettings; +use texturecraft_geom::{Bvh, Mesh}; + +/// What a texture set's bake reads to place its transfer rays, owned so a worker thread can use it +#[derive(Clone, Debug)] +pub struct BakeCageInputs { + pub(super) mesh: Arc, + pub(super) bvh: Arc, + pub(super) material: usize, + pub(super) settings: BakeSettings, + pub(super) high: MergedHigh, + pub(super) cage: Option>, + pub(super) skew: Option>, + pub(super) cage_paint: Option>, +} + +impl BakeCageInputs { + /// The cage the 3D view draws: the bake's ray origins at each triangle corner + pub fn cage_shell(&self) -> Result { + CageShell::new(&self.request()) + } + + /// Where each high-poly vertex sits relative to the bake's transfer rays + pub fn high_poly_reach(&self) -> Result { + HighPolyReach::new(&self.request()) + } + + fn request(&self) -> BakeRequest<'_> { + BakeRequest { + low_base_color: &[], + mesh: &self.mesh, + bvh: &self.bvh, + material: self.material, + settings: &self.settings, + high: Some(HighPoly { file_ids: &self.high.file_ids, mesh: &self.high.mesh, bvh: &self.high.bvh, base_color: &self.high.base_color }), + cage: self.cage.as_deref(), + skew: self.skew.as_deref(), + cage_paint: self.cage_paint.as_deref(), + tiles: (1, 1), + } + } +} diff --git a/crates/engine/src/bake/bake_meshes.rs b/crates/engine/src/bake/bake_meshes.rs index 260002db..da0e4a97 100644 --- a/crates/engine/src/bake/bake_meshes.rs +++ b/crates/engine/src/bake/bake_meshes.rs @@ -14,6 +14,11 @@ pub struct BakeMeshes { } impl BakeMeshes { + /// Every high poly appended into one mesh, as bakes see it + pub fn merged_high(&self) -> Option<&MergedHigh> { + self.merged.as_ref() + } + pub(crate) fn rebuild(&mut self) { self.merged = (!self.high.is_empty()).then(|| { let (mut mesh, mut base_color, mut file_ids) = (Mesh::default(), Vec::new(), Vec::new()); diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index e5982f18..b65d6ac8 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -8,6 +8,7 @@ use std::collections::BTreeMap; use std::sync::{Arc, OnceLock}; use texturecraft_core::BakePaintTarget; +use super::{BakeCageInputs, MergedHigh}; use crate::{BakeMesh, BakeTask}; use serde_json::{Value, json}; use texturecraft_bake::tracing::Tracer; @@ -15,6 +16,7 @@ use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress}; use texturecraft_core::{ BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion, }; +use texturecraft_geom::Mesh; use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; use crate::{EngineError, Result, Session, cmd}; @@ -90,8 +92,8 @@ fn parse_mesh(file_name: &str, bytes: Vec) -> Result { } impl Session { - pub fn bake_task(&self, ts: usize) -> Result { - let set = self.doc.project.texture_set(ts)?; + pub fn bake_task(&self, texture_set: usize) -> Result { + let set = self.doc.project.texture_set(texture_set)?; if !set.has_enabled_bake_tiles() { return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name))); } @@ -112,31 +114,22 @@ impl Session { } else { Arc::new(Vec::new()) }; - let high = if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }; - let cage = if high.is_some() && set.bake.cage.kind == texturecraft_core::CageType::CustomFile { - Some(self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?.mesh.clone()) - } else { - None - }; - let painted = |target| high.as_ref().and(self.doc.bake_paint.get(&(ts, target))).map(|map| super::layout::paint_for_bake(map, set)).transpose(); - let skew = painted(BakePaintTarget::Skew)?; - let cage_paint = painted(BakePaintTarget::Cage)?; + + let high = self.bake_high(texture_set)?; + let cage = self.bake_cage(texture_set, high.is_some())?; + let skew = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Skew)?; + let cage_paint = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Cage)?; + let grid = set.tile_grid(); let tiles = grid.map_or((1, 1), |grid| (grid.cols, grid.rows)); let excluded_tiles: Vec<_> = set.uv_tiles.iter().filter(|tile| set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid?.block(*tile)).collect(); - let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&ts).cloned().unwrap_or_default() }; + let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() }; + let tracer = GPU_TRACER.get().cloned(); Ok(BakeTask { low_base_color, - ts, - mesh: match grid.filter(|_| !set.tile_resolutions.is_empty()) { - Some(grid) => { - let mut mesh = (*self.source).clone(); - mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array()))); - Arc::new(mesh) - } - None => self.mesh.clone(), - }, + ts: texture_set, + mesh: self.bake_mesh(texture_set)?, bvh: self.bvh.clone(), material: set.material, settings: set.bake.clone(), @@ -151,6 +144,61 @@ impl Session { }) } + /// What texture set `texture_set`'s bake reads to place its transfer rays; `None` when the set bakes without a high poly or misses its cage file + pub fn bake_cage_inputs(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + let Some(high) = self.bake_high(texture_set)? else { return Ok(None) }; + let Ok(cage) = self.bake_cage(texture_set, true) else { return Ok(None) }; + + Ok(Some(BakeCageInputs { + mesh: self.bake_mesh(texture_set)?, + bvh: self.bvh.clone(), + material: set.material, + settings: set.bake.clone(), + high, + cage, + skew: self.bake_paint(texture_set, true, BakePaintTarget::Skew)?, + cage_paint: self.bake_paint(texture_set, true, BakePaintTarget::Cage)?, + })) + } + + /// The merged high polys texture set `texture_set` bakes from, unless it bakes from the low poly + fn bake_high(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + Ok(if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }) + } + + /// Texture set `texture_set`'s cage mesh when it bakes from a high poly with a Custom File cage + fn bake_cage(&self, texture_set: usize, has_high: bool) -> Result>> { + let set = self.doc.project.texture_set(texture_set)?; + if !has_high || set.bake.cage.kind != texturecraft_core::CageType::CustomFile { + return Ok(None); + } + + let cage = self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?; + Ok(Some(cage.mesh.clone())) + } + + /// Texture set `texture_set`'s painted skew or cage map, used only when it bakes from a high poly + fn bake_paint(&self, texture_set: usize, has_high: bool, target: BakePaintTarget) -> Result>> { + let set = self.doc.project.texture_set(texture_set)?; + let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| has_high); + paint.map(|map| super::layout::paint_for_bake(map, set)).transpose() + } + + /// The low poly texture set `texture_set` bakes: UV tiles of mixed resolutions move into its atlas + fn bake_mesh(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + Ok(match set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) { + Some(grid) => { + let mut mesh = (*self.source).clone(); + mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array()))); + Arc::new(mesh) + } + None => self.mesh.clone(), + }) + } + /// Store a finished bake as one undo step pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { let tracer = output.tracer.clone(); diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 213e1ff6..16ff68a7 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -1,5 +1,6 @@ //! Baking tasks, commands, settings helpers, and the mesh-map baking API +mod bake_cage_inputs; mod bake_mesh; mod bake_meshes; mod bake_task; @@ -11,6 +12,7 @@ mod paint_command; mod preserve_tiles; mod tile_command; +pub use bake_cage_inputs::BakeCageInputs; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 95d66b4e..a145ccb2 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -4,6 +4,9 @@ use glam::{Vec2, Vec3, Vec4}; use crate::{GeomError, Result}; +/// An edge by the bits of its two end positions, the lower one first +type EdgePositions = ([u32; 3], [u32; 3]); + /// A contiguous index range drawn with one material. #[derive(Clone, Debug, PartialEq)] pub struct SubMesh { @@ -107,6 +110,37 @@ impl Mesh { .collect() } + /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)` + pub fn uv_seam_edges(&self) -> Vec> { + let bits = |position: Vec3| position.to_array().map(f32::to_bits); + (0..self.materials.len().max(1)) + .map(|material| { + // Each 3D edge (by position) with the vertex pairs of the triangles that use it, the lower position first + let mut sides: std::collections::HashMap> = std::collections::HashMap::new(); + for triangle in self.triangles_of(material) { + let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue }; + + for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] { + let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else { continue }; + let (from_bits, to_bits) = (bits(*from_position), bits(*to_position)); + let side = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) }; + sides.entry(side.0).or_default().push(side.1); + } + } + + let uv = |index: u32| self.uvs.get(index as usize).copied(); + let mut seams: Vec<(u32, u32)> = sides + .into_values() + .filter(|pairs| pairs.iter().any(|&(from, to)| (uv(from), uv(to)) != (uv(pairs[0].0), uv(pairs[0].1)))) + .flat_map(|pairs| pairs.into_iter().map(|(from, to)| (from.min(to), from.max(to)))) + .collect(); + seams.sort_unstable(); + seams.dedup(); + seams + }) + .collect() + } + /// Material of triangle `t`. pub fn material_of(&self, t: usize) -> Option { let idx = (t * 3) as u32; @@ -433,6 +467,26 @@ mod tests { assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); } + #[test] + fn uv_seams_are_where_the_uv_layout_splits() { + let mesh = quad(); + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam"); + + // Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut + let mut seam = mesh.clone(); + seam.positions.push(seam.positions[0]); + seam.normals.push(seam.normals[0]); + seam.tangents.push(seam.tangents[0]); + seam.uvs.push(Vec2::new(0.9, 0.9)); + seam.indices[3] = 4; + assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + + // The same split with the same UV is a hard edge, not a seam + let mut hard = seam.clone(); + hard.uvs[4] = hard.uvs[0]; + assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]); + } + #[test] fn validate_catches_bad_indices() { let mut m = quad(); diff --git a/crates/render/src/bake_visualization.rs b/crates/render/src/bake_visualization.rs new file mode 100644 index 00000000..8dbc4927 --- /dev/null +++ b/crates/render/src/bake_visualization.rs @@ -0,0 +1,12 @@ +//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the UV seams and the low poly + +/// Which parts of the bake setup the 3D view draws +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BakeVisualization { + pub high_poly: bool, + pub cage: bool, + pub uv_seams: bool, + pub low_poly: bool, + /// Draw the cage, seams and low poly of only this texture set + pub only_set: Option, +} diff --git a/crates/render/src/cage_gpu.rs b/crates/render/src/cage_gpu.rs new file mode 100644 index 00000000..3ed4f13f --- /dev/null +++ b/crates/render/src/cage_gpu.rs @@ -0,0 +1,9 @@ +/// One texture set's cage on the GPU: three corners per triangle and the wireframe's corner pairs +pub(crate) struct CageGpu { + /// Identifies the corners' order and the edges: a new distance with the same topology only rewrites `corners` + pub(crate) topology: u64, + pub(crate) corners: wgpu::Buffer, + pub(crate) corner_count: u32, + pub(crate) edges: wgpu::Buffer, + pub(crate) edge_index_count: u32, +} diff --git a/crates/render/src/high_poly_gpu.rs b/crates/render/src/high_poly_gpu.rs new file mode 100644 index 00000000..97da6861 --- /dev/null +++ b/crates/render/src/high_poly_gpu.rs @@ -0,0 +1,11 @@ +/// The high poly bake mode draws over the low poly +pub(crate) struct HighPolyGpu { + /// Which mesh the buffers hold + pub(crate) id: u64, + pub(crate) vertices: wgpu::Buffer, + pub(crate) vertex_count: usize, + pub(crate) indices: wgpu::Buffer, + pub(crate) index_count: u32, + /// One value per vertex: 1 where the bake's rays miss it (drawn red), 0 where they reach it + pub(crate) missed: wgpu::Buffer, +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index c5ca2221..bb0967c7 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -13,12 +13,15 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bake_visualization; +mod cage_gpu; pub mod displace; #[cfg(not(target_arch = "wasm32"))] pub mod gpu_bake; pub mod gpu_trace; #[cfg(not(target_arch = "wasm32"))] pub mod headless; +mod high_poly_gpu; pub mod ibl; pub mod mesh_maps; pub mod readback; @@ -26,7 +29,9 @@ pub mod renderer; pub mod set_highlight; mod subdivide; pub mod trace; +mod uv_seam_gpu; +pub use bake_visualization::BakeVisualization; pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale}; pub use set_highlight::SetHighlight; pub use wgpu; diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 4ce9dac3..a2da0223 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -30,10 +30,14 @@ use texturecraft_geom::glam::{Mat4, Vec3}; use texturecraft_geom::{Mesh, OrbitCamera}; use texturecraft_texel::TILE; +use crate::bake_visualization::BakeVisualization; +use crate::cage_gpu::CageGpu; use crate::gpu_trace::{Checked, checked}; +use crate::high_poly_gpu::HighPolyGpu; use crate::ibl; use crate::set_highlight::SetHighlight; use crate::subdivide::{self, Vertex}; +use crate::uv_seam_gpu::UvSeamGpu; pub const MSAA: u32 = 4; pub const COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; @@ -173,6 +177,8 @@ pub struct Shade { /// Move the surface by the height channel (3D view): a dense copy of the mesh, displaced in /// the vertex shader at the height-to-normal strength. pub displacement: bool, + /// Bake mode's high poly, cage and UV seams over the 3D view + pub bake: Option, } /// The viewport's subsurface scattering approximation: the diffuse lighting wraps around the @@ -259,6 +265,7 @@ impl Default for Shade { sss_blur: None, refraction: false, displacement: false, + bake: None, } } } @@ -530,6 +537,11 @@ pub struct Renderer { wire3d_pipeline: wgpu::RenderPipeline, /// The highlighted set's mesh edges, wider and in the highlight color highlight_pipeline: wgpu::RenderPipeline, + /// Bake mode: the high poly, the cage's faces and wireframe, the low poly's UV seams + bake_high_pipeline: wgpu::RenderPipeline, + cage_pipeline: wgpu::RenderPipeline, + cage_wire_pipeline: wgpu::RenderPipeline, + uv_seam_pipeline: wgpu::RenderPipeline, bg_pipeline: wgpu::RenderPipeline, blit_pipeline: wgpu::RenderPipeline, post_pipeline: wgpu::RenderPipeline, @@ -563,6 +575,10 @@ pub struct Renderer { /// accumulation. content_rev: u64, mesh: Option, + bake_high: Option, + /// Each texture set's cage, by set index + cages: Vec>, + uv_seams: Option, sets: Vec, /// Viewport texture resolution: display textures at 1/2^shift of each set's size (at least /// as reduced as the device's texture limit needs). @@ -808,20 +824,31 @@ fn halton(mut i: u32, base: u32) -> f32 { const CLEAR: wgpu::LoadOp = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT); +/// Depth bias of the shadow map, per unit of surface slope: keeps lit surfaces from shadowing themselves +const SHADOW_SLOPE_BIAS: f32 = 1.5; + +/// Anisotropic filtering of the texture sets' sampler +const MAX_ANISOTROPY: u16 = 8; + +/// Size of the environment texture before the first environment loads +const PLACEHOLDER_ENV_SIZE: [u32; 2] = [512, 256]; + impl Renderer { /// `target_format`: the format of the pass [`Renderer::blit`] draws into. pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, target_format: wgpu::TextureFormat) -> Renderer { let shader = |label: &str, source: &str| { device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) }) }; - let module = shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl"))); + let module = + shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl"), "\n", include_str!("shaders/bake_view.wgsl"))); let util_module = shader("tc_util", include_str!("shaders/util.wgsl")); let post_module = shader("tc_post", concat!(include_str!("shaders/util.wgsl"), include_str!("shaders/post.wgsl"), include_str!("shaders/fx.wgsl"))); let shadow_module = shader("tc_shadow", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/shadow.wgsl"))); - let bgl = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| { + + let bind_group_layout = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries }) }; - let globals_bgl = bgl( + let globals_bind_group_layout = bind_group_layout( "tc_globals", &[ uniform_entry(0), @@ -838,44 +865,47 @@ impl Renderer { fragment_entry(4, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison)), ], ); - // The display textures, the aux texture, the sampler. + // The display textures, the aux texture, the sampler let textures = DisplayKind::ALL.len() as u32 + 1; - // Displacement reads the height (and the sampler) in the vertex shader. - let height = DisplayKind::ALL.iter().position(|k| *k == DisplayKind::Height).unwrap_or(0) as u32; + // Displacement reads the height (and the sampler) in the vertex shader + let height = DisplayKind::ALL.iter().position(|kind| *kind == DisplayKind::Height).unwrap_or(0) as u32; let set_entries: Vec<_> = (0..textures) .map(tex_entry) .chain(std::iter::once(sampler_entry(textures))) - .map(|mut e| { - if e.binding == height || e.binding == textures { - e.visibility |= wgpu::ShaderStages::VERTEX; + .map(|mut entry| { + if entry.binding == height || entry.binding == textures { + entry.visibility |= wgpu::ShaderStages::VERTEX; } - e + entry }) .collect(); - let set_bgl = bgl("tc_set", &set_entries); - let refr_bgl = bgl("tc_refr", &[tex_entry(0)]); - let blit_bgl = bgl("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]); - let mip_bgl = bgl("tc_mip", &[tex_entry(0), sampler_entry(1)]); - let fx_bgl = bgl("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]); - let shadow_bgl = bgl("tc_shadow", &[uniform_entry(0)]); - let pl = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| { + let set_bind_group_layout = bind_group_layout("tc_set", &set_entries); + let refraction_bind_group_layout = bind_group_layout("tc_refr", &[tex_entry(0)]); + let blit_bind_group_layout = bind_group_layout("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]); + let mip_bind_group_layout = bind_group_layout("tc_mip", &[tex_entry(0), sampler_entry(1)]); + let effect_bind_group_layout = + bind_group_layout("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]); + let shadow_bind_group_layout = bind_group_layout("tc_shadow", &[uniform_entry(0)]); + + let pipeline_layout = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| { device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: groups, immediate_size: 0 }) }; - let layout = pl("tc_uv", &[Some(&globals_bgl), Some(&set_bgl)]); - let mesh_layout = pl("tc_mesh", &[Some(&globals_bgl), Some(&set_bgl), Some(&refr_bgl)]); - let bg_layout = pl("tc_bg", &[Some(&globals_bgl)]); - let blit_layout = pl("tc_blit", &[Some(&blit_bgl)]); - let fx_layout = pl("tc_fx", &[Some(&fx_bgl)]); - let shadow_layout = pl("tc_shadow", &[Some(&shadow_bgl), Some(&set_bgl)]); - let vb = [Some(wgpu::VertexBufferLayout { + let layout = pipeline_layout("tc_uv", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout)]); + let mesh_layout = pipeline_layout("tc_mesh", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout), Some(&refraction_bind_group_layout)]); + let background_layout = pipeline_layout("tc_bg", &[Some(&globals_bind_group_layout)]); + let blit_layout = pipeline_layout("tc_blit", &[Some(&blit_bind_group_layout)]); + let effect_layout = pipeline_layout("tc_fx", &[Some(&effect_bind_group_layout)]); + let shadow_layout = pipeline_layout("tc_shadow", &[Some(&shadow_bind_group_layout), Some(&set_bind_group_layout)]); + + let vertex_layout = [Some(wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as u64, step_mode: wgpu::VertexStepMode::Vertex, attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x4, 3 => Float32x2], })]; - // shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode - // (e.g. RGBM) if WebGL2 without float color buffers turns out to matter. + + // shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode (e.g. RGBM) if WebGL2 without float color buffers turns out to matter let hdr_format = if hdr_renderable(device) { HDR_FORMAT } else { COLOR_FORMAT }; - let hdr = |fs, blend| Some((fs, hdr_format, blend)); + let hdr_target = |fragment_entry_point, blend| Some((fragment_entry_point, hdr_format, blend)); let always = || Some(depth_state(false, wgpu::CompareFunction::Always)); let mesh_pipeline = pipeline( device, @@ -883,8 +913,8 @@ impl Renderer { &mesh_layout, &module, "vs_mesh", - &vb, - hdr("fs_mesh", None), + &vertex_layout, + hdr_target("fs_mesh", None), MSAA, Some(depth_state(true, wgpu::CompareFunction::Less)), ); @@ -894,31 +924,103 @@ impl Renderer { &mesh_layout, &module, "vs_mesh", - &vb, - hdr("fs_opaque", None), + &vertex_layout, + hdr_target("fs_opaque", None), MSAA, Some(depth_state(true, wgpu::CompareFunction::Less)), ); - let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vb, hdr("fs_uv", None), MSAA, always()); + let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_uv", None), MSAA, always()); let blend = Some(wgpu::BlendState::ALPHA_BLENDING); - let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vb, hdr("fs_wire", blend), MSAA, always()); + let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_wire", blend), MSAA, always()); let wire3d_depth = Some(depth_state(false, wgpu::CompareFunction::LessEqual)); - let wire3d_pipeline = pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vb, hdr("fs_wire3d", blend), MSAA, wire3d_depth.clone()); - let highlight_pipeline = - pipeline(device, "tc_highlight", &layout, &module, "vs_wire_highlight", &vb, hdr("fs_wire_highlight", blend), MSAA, wire3d_depth); - let bg_pipeline = pipeline(device, "tc_bg", &bg_layout, &module, "vs_bg", &[], hdr("fs_bg", None), MSAA, always()); + let wire3d_pipeline = + pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire3d", blend), MSAA, wire3d_depth.clone()); + let highlight_pipeline = pipeline( + device, + "tc_highlight", + &layout, + &module, + "vs_wire_highlight", + &vertex_layout, + hdr_target("fs_wire_highlight", blend), + MSAA, + wire3d_depth.clone(), + ); + + let [mesh_vertex_layout] = vertex_layout.clone(); + let high_layout = [ + mesh_vertex_layout, + Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array![4 => Float32], + }), + ]; + let bake_high_pipeline = pipeline( + device, + "tc_bake_high", + &background_layout, + &module, + "vs_bake_high", + &high_layout, + hdr_target("fs_bake_high", None), + MSAA, + Some(depth_state(true, wgpu::CompareFunction::Less)), + ); + let corner_layout = [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::<[f32; 3]>() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array![0 => Float32x3], + })]; + let cage_pipeline = pipeline( + device, + "tc_cage", + &background_layout, + &module, + "vs_bake_cage", + &corner_layout, + hdr_target("fs_bake_cage", blend), + MSAA, + wire3d_depth.clone(), + ); + let cage_wire_pipeline = pipeline( + device, + "tc_cage_wire", + &background_layout, + &module, + "vs_bake_cage_wire", + &corner_layout, + hdr_target("fs_wire_bake_cage", blend), + MSAA, + wire3d_depth.clone(), + ); + let uv_seam_pipeline = + pipeline(device, "tc_uv_seam", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire_uv_seam", blend), MSAA, wire3d_depth.clone()); + let bg_pipeline = pipeline(device, "tc_bg", &background_layout, &module, "vs_bg", &[], hdr_target("fs_bg", None), MSAA, always()); let blit_pipeline = pipeline(device, "tc_blit", &blit_layout, &util_module, "vs_blit", &[], Some(("fs_blit", target_format, None)), 1, None); - let post_pipeline = pipeline(device, "tc_post", &fx_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); - let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))] - .map(|(fs, blend)| pipeline(device, "tc_bloom", &fx_layout, &post_module, "vs_full", &[], hdr(fs, blend), 1, None)); - let gbuf_pipeline = - pipeline(device, "tc_gbuf", &mesh_layout, &module, "vs_mesh", &vb, hdr("fs_gbuf", None), 1, Some(depth_state(true, wgpu::CompareFunction::Less))); - let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fs| pipeline(device, "tc_sss", &fx_layout, &post_module, "vs_full", &[], hdr(fs, None), 1, None)); - let dof_pipeline = pipeline(device, "tc_dof", &fx_layout, &post_module, "vs_full", &[], hdr("fs_dof", None), 1, None); + let post_pipeline = pipeline(device, "tc_post", &effect_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); + let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))].map(|(fragment_entry_point, blend)| { + pipeline(device, "tc_bloom", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, blend), 1, None) + }); + let gbuffer_pipeline = pipeline( + device, + "tc_gbuf", + &mesh_layout, + &module, + "vs_mesh", + &vertex_layout, + hdr_target("fs_gbuf", None), + 1, + Some(depth_state(true, wgpu::CompareFunction::Less)), + ); + let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fragment_entry_point| { + pipeline(device, "tc_sss", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, None), 1, None) + }); + let dof_pipeline = pipeline(device, "tc_dof", &effect_layout, &post_module, "vs_full", &[], hdr_target("fs_dof", None), 1, None); let dof_target = Some(wgpu::ColorTargetState { format: hdr_format, blend: None, write_mask: wgpu::ColorWrites::ALL }); let dof_gather_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("tc_dof_gather"), - layout: Some(&fx_layout), + layout: Some(&effect_layout), vertex: wgpu::VertexState { module: &post_module, entry_point: Some("vs_full"), buffers: &[], compilation_options: Default::default() }, primitive: wgpu::PrimitiveState::default(), depth_stencil: None, @@ -932,20 +1034,23 @@ impl Renderer { multiview_mask: None, cache: None, }); + let shadow_depth = wgpu::DepthStencilState { - bias: wgpu::DepthBiasState { constant: 0, slope_scale: 1.5, clamp: 0.0 }, + bias: wgpu::DepthBiasState { constant: 0, slope_scale: SHADOW_SLOPE_BIAS, clamp: 0.0 }, ..depth_state(true, wgpu::CompareFunction::Less) }; - let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vb, None, 1, Some(shadow_depth)); - // accum = hdr * k + accum * (1 - k) with k = 1 / (sample + 1): a running average. + let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vertex_layout, None, 1, Some(shadow_depth)); + + // accum = hdr_target * k + accum * (1 - k) with k = 1 / (sample + 1): a running average let average = wgpu::BlendComponent { src_factor: wgpu::BlendFactor::Constant, dst_factor: wgpu::BlendFactor::OneMinusConstant, operation: wgpu::BlendOperation::Add, }; - let accum_layout = pl("tc_accum", &[Some(&mip_bgl)]); + let accum_layout = pipeline_layout("tc_accum", &[Some(&mip_bind_group_layout)]); let accum_blend = Some(wgpu::BlendState { color: average, alpha: average }); - let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr("fs_copy", accum_blend), 1, None); + let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr_target("fs_copy", accum_blend), 1, None); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("tc_tex"), address_mode_u: wgpu::AddressMode::ClampToEdge, @@ -953,7 +1058,7 @@ impl Renderer { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::MipmapFilterMode::Linear, - anisotropy_clamp: 8, + anisotropy_clamp: MAX_ANISOTROPY, ..Default::default() }); let env_sampler = device.create_sampler(&wgpu::SamplerDescriptor { @@ -972,7 +1077,8 @@ impl Renderer { compare: Some(wgpu::CompareFunction::LessEqual), ..Default::default() }); - let shadow_buf = device.create_buffer(&wgpu::BufferDescriptor { + + let shadow_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("tc_shadow"), size: std::mem::size_of::<[[f32; 4]; 5]>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, @@ -986,39 +1092,45 @@ impl Renderer { vp: Mat4::IDENTITY, bg: device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_shadow"), - layout: &shadow_bgl, - entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buf.as_entire_binding() }], + layout: &shadow_bind_group_layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buffer.as_entire_binding() }], }), - buf: shadow_buf, + buf: shadow_buffer, }; + let black = Tex::new(device, "tc_black", 1, 1, COLOR_FORMAT, 1).view; - let refr_black = device.create_bind_group(&wgpu::BindGroupDescriptor { + let refraction_black = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_refr_black"), - layout: &refr_bgl, + layout: &refraction_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&black) }], }); - let env = Tex::new(device, "tc_env", 512, 256, wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); - let mut r = Renderer { + let env = Tex::new(device, "tc_env", PLACEHOLDER_ENV_SIZE[0], PLACEHOLDER_ENV_SIZE[1], wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); + + let mut renderer = Renderer { target_format, hdr_format, - globals_bgl, - set_bgl, - blit_bgl, - mip_bgl, - fx_bgl, - refr_bgl, - refr_black, + globals_bgl: globals_bind_group_layout, + set_bgl: set_bind_group_layout, + blit_bgl: blit_bind_group_layout, + mip_bgl: mip_bind_group_layout, + fx_bgl: effect_bind_group_layout, + refr_bgl: refraction_bind_group_layout, + refr_black: refraction_black, mesh_pipeline, opaque_pipeline, uv_pipeline, wire_pipeline, wire3d_pipeline, highlight_pipeline, + bake_high_pipeline, + cage_pipeline, + cage_wire_pipeline, + uv_seam_pipeline, bg_pipeline, blit_pipeline, post_pipeline, bloom_pipelines, - gbuf_pipeline, + gbuf_pipeline: gbuffer_pipeline, sss_pipelines, dof_gather_pipeline, dof_pipeline, @@ -1038,13 +1150,16 @@ impl Renderer { sh: [[0.0; 4]; 9], content_rev: 0, mesh: None, + bake_high: None, + cages: Vec::new(), + uv_seams: None, sets: Vec::new(), display_shift: 0, material_sets: Vec::new(), views: HashMap::new(), }; - r.set_environment(device, queue, "Studio Soft", None); - r + renderer.set_environment(device, queue, "Studio Soft", None); + renderer } pub fn environment_name(&self) -> &str { @@ -1124,6 +1239,79 @@ impl Renderer { self.content_rev += 1; } + /// Upload the high poly bake mode draws when `id` changed; `None` removes it + pub fn set_bake_high(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh: Option<&Mesh>, id: u64) { + if self.bake_high.as_ref().map(|high| high.id) == mesh.map(|_| id) { + return; + } + + self.bake_high = mesh.map(|mesh| HighPolyGpu { + id, + vertices: upload_buffer(device, queue, "tc_bake_high_vb", bytemuck::cast_slice(&subdivide::vertices(mesh)), wgpu::BufferUsages::VERTEX), + vertex_count: mesh.positions.len(), + indices: upload_buffer(device, queue, "tc_bake_high_ib", bytemuck::cast_slice(&mesh.indices), wgpu::BufferUsages::INDEX), + index_count: mesh.indices.len() as u32, + missed: upload_buffer(device, queue, "tc_bake_high_missed", bytemuck::cast_slice(&vec![0f32; mesh.positions.len()]), wgpu::BufferUsages::VERTEX), + }); + self.content_rev += 1; + } + + /// Which vertices of high poly `id` the bake's rays miss (1) or reach (0); ignored for another mesh or vertex count + pub fn set_bake_high_missed(&mut self, queue: &wgpu::Queue, id: u64, missed: &[f32]) { + let Some(high) = self.bake_high.as_ref().filter(|high| high.id == id && high.vertex_count == missed.len()) else { return }; + + queue.write_buffer(&high.missed, 0, bytemuck::cast_slice(missed)); + self.content_rev += 1; + } + + /// Texture set `texture_set`'s cage: `corners` three per triangle and `edges` as corner pairs; `None` removes it. The same `topology` as before only rewrites the corners + pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<(&[Vec3], &[[u32; 2]])>, topology: u64) { + if self.cages.len() <= texture_set { + self.cages.resize_with(texture_set + 1, || None); + } + let Some(slot) = self.cages.get_mut(texture_set) else { return }; + + match (cage, slot.as_mut()) { + (None, _) => *slot = None, + (Some((corners, _)), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == corners.len() => { + queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(corners)); + } + (Some((corners, edges)), _) => { + *slot = Some(CageGpu { + topology, + corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(corners), wgpu::BufferUsages::VERTEX), + corner_count: corners.len() as u32, + edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(edges), wgpu::BufferUsages::INDEX), + edge_index_count: (edges.len() * 2) as u32, + }); + } + } + self.content_rev += 1; + } + + /// Forget the cages of texture sets from `count` on (sets that were removed) + pub fn truncate_bake_cages(&mut self, count: usize) { + if self.cages.len() > count { + self.cages.truncate(count); + self.content_rev += 1; + } + } + + /// The low poly's UV seams as vertex pairs per material ([`Mesh::uv_seam_edges`]) for mesh `mesh_id` + pub fn set_uv_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) { + let mut line_indices: Vec = Vec::new(); + let mut line_draws = Vec::new(); + for (material, edges) in seams.iter().enumerate() { + let start = line_indices.len() as u32; + line_indices.extend(edges.iter().flat_map(|&(from, to)| [from, to])); + line_draws.push((start, line_indices.len() as u32 - start, material)); + } + + let lines = upload_buffer(device, queue, "tc_uv_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX); + self.uv_seams = Some(UvSeamGpu { mesh_id, lines, line_draws }); + self.content_rev += 1; + } + /// Build the mesh's dense copy for displacement (once per mesh). fn ensure_dense(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) { let Some(m) = self.mesh.as_mut() else { return }; @@ -1889,30 +2077,30 @@ impl Renderer { self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, highlight, refr); } - /// One scene pass: background, then the mesh with `pipe`, the wireframe with `wire` and one set's highlighted edges with `highlight` + /// One scene pass: background, then the mesh with `mesh_pipeline`, the wireframe with `wire` and one set's highlighted edges with `highlight` #[allow(clippy::too_many_arguments)] fn draw_scene( &self, encoder: &mut wgpu::CommandEncoder, - v: &ViewTargets, + targets: &ViewTargets, resolve: &wgpu::TextureView, - globals_bg: &wgpu::BindGroup, + globals_bind_group: &wgpu::BindGroup, frame: &Frame, - pipe: &wgpu::RenderPipeline, + mesh_pipeline: &wgpu::RenderPipeline, wire: Option<&wgpu::RenderPipeline>, highlight: Option<(&wgpu::RenderPipeline, usize)>, - refr: &wgpu::BindGroup, + refraction_source: &wgpu::BindGroup, ) { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("tc_view"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &v.msaa, + view: &targets.msaa, resolve_target: Some(resolve), depth_slice: None, ops: wgpu::Operations { load: CLEAR, store: wgpu::StoreOp::Discard }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &v.depth, + view: &targets.depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }), stencil_ops: None, }), @@ -1920,33 +2108,86 @@ impl Renderer { occlusion_query_set: None, multiview_mask: None, }); - pass.set_bind_group(0, globals_bg, &[]); + pass.set_bind_group(0, globals_bind_group, &[]); pass.set_pipeline(&self.bg_pipeline); pass.draw(0..3, 0..1); - let Some(m) = &self.mesh else { return }; - let uv_ts = match frame.kind { + let Some(mesh) = &self.mesh else { return }; + + let uv_set = match frame.kind { ViewKind::Scene => None, ViewKind::Uv { ts, .. } => Some(ts), }; - pass.set_bind_group(2, refr, &[]); - let geo = self.geometry(m, frame); - // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) + pass.set_bind_group(2, refraction_source, &[]); + let geometry = self.geometry(mesh, frame); let (highlight, highlight_set) = highlight.unzip(); + let bake = frame.shade.bake.filter(|_| uv_set.is_none()); + let low_poly_shown = bake.is_none_or(|bake| bake.low_poly); + let low_poly_set = bake.and_then(|bake| bake.only_set).or(uv_set); + // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) let passes = [ - (Some(pipe), &geo.vb, &geo.ib, &geo.draws, uv_ts, 1), - (wire, &m.geo.vb, &m.lines, &m.line_draws, uv_ts, 1), - (highlight, &m.geo.vb, &m.lines, &m.line_draws, highlight_set, HIGHLIGHT_SHIFTS), + (Some(mesh_pipeline).filter(|_| low_poly_shown), &geometry.vb, &geometry.ib, &geometry.draws, low_poly_set, 1), + (wire, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_set, 1), + (highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS), ]; - for (pipe, vb, ib, ranges, only, instances) in passes { - let Some(pipe) = pipe else { continue }; - pass.set_pipeline(pipe); - pass.set_vertex_buffer(0, vb.slice(..)); - pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(ranges, &frame.visible, only) { + for (pipeline, vertices, indices, ranges, only_set, instances) in passes { + let Some(pipeline) = pipeline else { continue }; + + pass.set_pipeline(pipeline); + pass.set_vertex_buffer(0, vertices.slice(..)); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + for (range, set) in self.drawable(ranges, &frame.visible, only_set) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..instances); } } + + if let Some(bake) = bake { + self.draw_bake(&mut pass, mesh, frame, bake); + } + } + + /// Bake mode's high poly, UV seams and cages over the low poly `low_poly` + fn draw_bake(&self, pass: &mut wgpu::RenderPass<'_>, low_poly: &MeshGpu, frame: &Frame, bake: BakeVisualization) { + if bake.high_poly + && let Some(high) = &self.bake_high + { + pass.set_pipeline(&self.bake_high_pipeline); + pass.set_vertex_buffer(0, high.vertices.slice(..)); + pass.set_vertex_buffer(1, high.missed.slice(..)); + pass.set_index_buffer(high.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..high.index_count, 0, 0..1); + } + + if bake.uv_seams + && let Some(seams) = self.uv_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id) + { + pass.set_pipeline(&self.uv_seam_pipeline); + pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..)); + pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); + for (range, set) in self.drawable(&seams.line_draws, &frame.visible, bake.only_set) { + pass.set_bind_group(1, &set.bind_group, &[]); + pass.draw_indexed(range, 0, 0..1); + } + } + + if !bake.cage { + return; + } + + let shown = |texture_set: usize| bake.only_set.is_none_or(|only| only == texture_set) && frame.visible.get(texture_set).copied().unwrap_or(true); + let cages = || self.cages.iter().enumerate().filter(move |(texture_set, _)| shown(*texture_set)).filter_map(|(_, cage)| cage.as_ref()); + // The translucent faces first, then the wireframe over them + pass.set_pipeline(&self.cage_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.draw(0..cage.corner_count, 0..1); + } + pass.set_pipeline(&self.cage_wire_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..cage.edge_index_count, 0, 0..1); + } } /// Draw view `id` into the current pass at `rect` (target pixels: x, y, w, h). diff --git a/crates/render/src/shaders/bake_view.wgsl b/crates/render/src/shaders/bake_view.wgsl new file mode 100644 index 00000000..1985f980 --- /dev/null +++ b/crates/render/src/shaders/bake_view.wgsl @@ -0,0 +1,88 @@ +// Bake mode's 3D view: the high poly, the cage around the low poly and the UV seams + +struct BakeViewOut { + @builtin(position) clip: vec4, + @location(0) world_position: vec3, + @location(1) normal: vec3, + // 1 where the bake's rays miss the high poly, 0 where they reach it + @location(2) missed: f32, +}; + +const HIGH_POLY_COLOR: vec3 = vec3(0.10, 0.36, 0.56); +const MISSED_COLOR: vec3 = vec3(0.80, 0.01, 0.01); +const CAGE_COLOR: vec3 = vec3(0.55, 0.42, 0.26); +const CAGE_OPACITY: f32 = 0.16; +const CAGE_WIRE_COLOR: vec4 = vec4(0.75, 0.62, 0.42, 0.7); +const UV_SEAM_COLOR: vec4 = vec4(0.20, 0.85, 0.30, 1.0); + +// Brightness of surfaces seen edge-on; facing the camera adds the rest +const HEADLIGHT_AMBIENT: f32 = 0.3; + +// Fractions of the way to the camera each vertex moves, so near-coincident surfaces and lines draw in a fixed order +const HIGH_POLY_PULL_TOWARD_EYE: f32 = 0.001; +const CAGE_WIRE_PULL_TOWARD_EYE: f32 = 0.002; + +// Lit from the camera: surfaces facing it are brightest +fn headlight(color: vec3, normal: vec3, world_position: vec3) -> vec3 { + let facing = abs(dot(normal, normalize(g.eye.xyz - world_position))); + return color * (HEADLIGHT_AMBIENT + (1.0 - HEADLIGHT_AMBIENT) * facing); +} + +fn pulled_toward_eye(world_position: vec3, fraction: f32) -> vec4 { + return g.view_proj * vec4(world_position + (g.eye.xyz - world_position) * fraction, 1.0); +} + +// Pulled slightly toward the camera: where the high poly nearly touches the low poly it shows instead of flickering with it +@vertex +fn vs_bake_high(@location(0) position: vec3, @location(1) normal: vec3, @location(4) missed: f32) -> BakeViewOut { + var out: BakeViewOut; + out.clip = pulled_toward_eye(position, HIGH_POLY_PULL_TOWARD_EYE); + out.world_position = position; + out.normal = normal; + out.missed = missed; + return out; +} + +@fragment +fn fs_bake_high(surface: BakeViewOut) -> @location(0) vec4 { + let color = mix(HIGH_POLY_COLOR, MISSED_COLOR, surface.missed); + return vec4(headlight(color, normalize(surface.normal), surface.world_position), 1.0); +} + +@vertex +fn vs_bake_cage(@location(0) position: vec3) -> BakeViewOut { + var out: BakeViewOut; + out.clip = g.view_proj * vec4(position, 1.0); + out.world_position = position; + out.normal = vec3(0.0, 1.0, 0.0); + out.missed = 0.0; + return out; +} + +// The cage's own faces: their normal comes from the screen-space change of the position +@fragment +fn fs_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { + let face_normal = normalize(cross(dpdx(surface.world_position), dpdy(surface.world_position))); + return vec4(headlight(CAGE_COLOR, face_normal, surface.world_position), CAGE_OPACITY); +} + +// Pulled toward the camera like the 3D wireframe, so the lines win against the cage's faces +@vertex +fn vs_bake_cage_wire(@location(0) position: vec3) -> BakeViewOut { + var out: BakeViewOut; + out.clip = pulled_toward_eye(position, CAGE_WIRE_PULL_TOWARD_EYE); + out.world_position = position; + out.normal = vec3(0.0, 1.0, 0.0); + out.missed = 0.0; + return out; +} + +@fragment +fn fs_wire_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { + return CAGE_WIRE_COLOR; +} + +@fragment +fn fs_wire_uv_seam(surface: VOut) -> @location(0) vec4 { + return UV_SEAM_COLOR; +} diff --git a/crates/render/src/uv_seam_gpu.rs b/crates/render/src/uv_seam_gpu.rs new file mode 100644 index 00000000..0ac80dc9 --- /dev/null +++ b/crates/render/src/uv_seam_gpu.rs @@ -0,0 +1,8 @@ +/// The low poly's UV seams as a line list over its vertex buffer +pub(crate) struct UvSeamGpu { + /// The low-poly mesh the lines belong to + pub(crate) mesh_id: u64, + pub(crate) lines: wgpu::Buffer, + /// (first index, count, material) per material + pub(crate) line_draws: Vec<(u32, u32, usize)>, +} diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 864c70c3..d148a268 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -1,8 +1,9 @@ use texturecraft_compose::{DisplayKind, ImageRes}; +use texturecraft_geom::glam::Vec3; use texturecraft_geom::{OrbitCamera, primitives}; use texturecraft_render::headless::Headless; use texturecraft_render::renderer::TAA_SAMPLES; -use texturecraft_render::{Frame, Shade, ViewKind}; +use texturecraft_render::{BakeVisualization, Frame, Shade, ViewKind}; /// The UI's key light (`viewport::shade`). const LIGHT: [f32; 4] = [0.5, 0.8, 0.4, 2.5]; @@ -42,6 +43,9 @@ impl Img { } } +/// The id `setup` uploads the material ball under +const MESH_ID: u64 = 1; + /// A headless renderer with the material ball framed in a 480×360 view (None without a GPU). fn setup() -> Option<(Headless, Frame)> { let Ok(mut h) = Headless::new() else { @@ -49,7 +53,7 @@ fn setup() -> Option<(Headless, Frame)> { return None; }; let mesh = primitives::material_ball(); - h.renderer.set_mesh(&h.device, &h.queue, &mesh, 1); + h.renderer.set_mesh(&h.device, &h.queue, &mesh, MESH_ID); h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0), ((256, 256), 1)], 2); let mut cam = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() }; let (lo, hi) = mesh.bounds(); @@ -220,6 +224,73 @@ fn wireframe_3d_overlays_the_mesh() { assert_eq!(a.at(5, 5), b.at(5, 5), "the background stays clean"); } +#[test] +fn bake_visualization_draws_the_high_poly_and_the_cage() { + // A high poly inside the material ball, a cage around it, and how far a color must lead the others to count as that color + const HIGH_POLY_RADIUS_PER_SIZE: f32 = 0.3; + const CAGE_SCALE: f32 = 2.5; + const HIGH_POLY_ID: u64 = 7; + const CAGE_TOPOLOGY: u64 = 1; + const CAGE_EDGES: [[u32; 2]; 2] = [[0, 1], [1, 2]]; + const COLOR_LEAD: i32 = 30; + + let Some((mut h, frame)) = setup() else { return }; + let ball = primitives::material_ball(); + let (low_min, low_max) = ball.bounds(); + let ball_center = (low_min + low_max) * 0.5; + let mut high = primitives::sphere((low_max - low_min).max_element() * HIGH_POLY_RADIUS_PER_SIZE, 32, 16); + for position in &mut high.positions { + *position += ball_center; + } + h.renderer.set_bake_high(&h.device, &h.queue, Some(&high), HIGH_POLY_ID); + let corners: Vec = high.indices.iter().map(|index| (high.positions[*index as usize] - ball_center) * CAGE_SCALE + ball_center).collect(); + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&corners, &CAGE_EDGES)), CAGE_TOPOLOGY); + let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: true, only_set: None }; + let center = (frame.size[0] / 2, frame.size[1] / 2); + + let only = |h: &mut Headless, parts: BakeVisualization, name: &str| render(h, &shaded(&frame, |s| s.bake = Some(parts)), name); + let low_only = only(&mut h, bake, "bake_low_only"); + let hidden = only(&mut h, BakeVisualization { low_poly: false, ..bake }, "bake_low_hidden"); + let high_poly = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_poly"); + let caged = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage"); + assert_same(&low_only, &render(&mut h, &frame, "bake_off"), "every part off draws only the low poly"); + let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_background"); + assert_same(&hidden, &background, "without the low poly only the background is left"); + let [red, green, blue] = high_poly.at(center.0, center.1).map(i32::from); + assert!(blue > red + COLOR_LEAD && blue > green, "the high poly inside the low poly draws blue: {:?}", [red, green, blue]); + let ([low_red, low_green, low_blue], [caged_red, caged_green, caged_blue]) = (low_only.at(center.0, center.1), caged.at(center.0, center.1)); + assert!( + caged_blue < low_blue && caged_red >= caged_blue && caged_green >= caged_blue, + "the cage tints the ball tan: {:?} → {:?}", + [low_red, low_green, low_blue], + [caged_red, caged_green, caged_blue] + ); + + // Vertices the bake's rays miss turn red + h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![1.0; high.positions.len()]); + let missed = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_missed"); + let [red, green, blue] = missed.at(center.0, center.1).map(i32::from); + assert!(red > blue + COLOR_LEAD && red > green + COLOR_LEAD, "missed vertices draw red: {:?}", [red, green, blue]); + + // Show for selected texture set only: the other set's low poly and the cage of set 0 drop out + let first_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(0), ..bake }, "bake_only_first_set"); + let second_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(1), ..bake }, "bake_only_second_set"); + assert_ne!(first_set.px, caged.px, "the second set's low poly is left out"); + assert_ne!(second_set.px, caged.px, "the first set's low poly and cage are left out"); + assert_ne!(first_set.px, second_set.px); + + // UV seams draw over the low poly + h.renderer.set_uv_seams(&h.device, &h.queue, MESH_ID, &ball.uv_seam_edges()); + let seams = only(&mut h, BakeVisualization { uv_seams: true, ..bake }, "bake_uv_seams"); + assert_ne!(seams.px, low_only.px, "the seams show"); + + // A new distance with the same topology only moves the corners + let grown: Vec = corners.iter().map(|corner| (*corner - ball_center) * 2.0 + ball_center).collect(); + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&grown, &CAGE_EDGES)), CAGE_TOPOLOGY); + let bigger = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage_grown"); + assert_ne!(caged.px, bigger.px, "the cage grew"); +} + #[test] fn ortho_background_matches_perspective() { let Some((mut h, frame)) = setup() else { return }; diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs new file mode 100644 index 00000000..42da4393 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs @@ -0,0 +1,61 @@ +use egui::collapsing_header::CollapsingState; +use egui::{Rect, Ui, vec2}; +use egui_phosphor::regular as icon; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::theme::Tokens; +use crate::widgets::{icon_button_without_tooltip, section_chevron}; + +/// The panel's width and its gap from the 3D view's top-left corner +const PANEL_WIDTH: f32 = 280.0; +const PANEL_MARGIN: f32 = 12.0; + +/// Size of the panel's eye buttons +const EYE_BUTTON_SIZE: f32 = 22.0; + +/// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view` +pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) { + let toggles = &mut app.ui.bake_visualization; + egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show( + ui.ctx(), + |ui| { + ui.set_width(PANEL_WIDTH); + let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("bake_visualization_open"), true); + let header = eye_row(ui, &mut toggles.on, tr("Baking Visualization"), Some(collapsing_state.is_open())); + if header.clicked() { + collapsing_state.toggle(ui); + } + + collapsing_state.show_body_unindented(ui, |ui| { + ui.add_enabled_ui(toggles.on, |ui| { + ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only")); + eye_row(ui, &mut toggles.high_poly, tr("High Definition Mesh (HP)"), None); + eye_row(ui, &mut toggles.cage, tr("Cage"), None); + eye_row(ui, &mut toggles.uv_seams, tr("UV Seams"), None); + eye_row(ui, &mut toggles.low_poly, tr("Project Mesh (LP)"), None); + }); + }); + }, + ); +} + +/// A row with `label`, a chevron when `open` is given, and an eye button on the right that switches `shown`; returns the label's response +fn eye_row(ui: &mut Ui, shown: &mut bool, label: &str, open: Option) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.set_min_height(EYE_BUTTON_SIZE); + let text = match open { + Some(is_open) => egui::RichText::new(format!("{} {label}", section_chevron(ui, is_open).text())), + None => egui::RichText::new(label), + }; + let response = ui.add(egui::Label::new(text.color(tokens.text_strong)).selectable(false).sense(egui::Sense::click())); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icon_button_without_tooltip(ui, if *shown { icon::EYE } else { icon::EYE_SLASH }, label, false, EYE_BUTTON_SIZE).clicked() { + *shown = !*shown; + } + }); + response + }) + .inner +} diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs new file mode 100644 index 00000000..0603c523 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs @@ -0,0 +1,34 @@ +use serde::{Deserialize, Serialize}; +use texturecraft_render::BakeVisualization; + +/// The Baking Visualization panel's switches in bake mode's 3D view +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct BakeVisualizationToggles { + /// The panel's eye: the whole visualization on or off + pub on: bool, + pub selected_set_only: bool, + pub high_poly: bool, + pub cage: bool, + pub uv_seams: bool, + pub low_poly: bool, +} + +impl Default for BakeVisualizationToggles { + fn default() -> Self { + Self { on: true, selected_set_only: false, high_poly: true, cage: true, uv_seams: false, low_poly: true } + } +} + +impl BakeVisualizationToggles { + /// What the renderer draws with these switches while texture set `selected_set` is selected + pub fn visualization(&self, selected_set: usize) -> Option { + self.on.then_some(BakeVisualization { + high_poly: self.high_poly, + cage: self.cage, + uv_seams: self.uv_seams, + low_poly: self.low_poly, + only_set: self.selected_set_only.then_some(selected_set), + }) + } +} diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 3a308a4a..70dd4225 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -1,9 +1,13 @@ //! Bake Mode presentation; persisted settings live in core and edits use engine commands mod bake_paint_brush; +mod bake_visualization_panel; +mod bake_visualization_toggles; mod breadcrumb; mod common_settings; pub use bake_paint_brush::BakePaintBrush; +pub(crate) use bake_visualization_panel::bake_visualization_panel; +pub use bake_visualization_toggles::BakeVisualizationToggles; mod controls; mod map_settings; mod mesh_map_bakers; diff --git a/crates/ui-egui/src/bake_scene.rs b/crates/ui-egui/src/bake_scene.rs new file mode 100644 index 00000000..1a30780e --- /dev/null +++ b/crates/ui-egui/src/bake_scene.rs @@ -0,0 +1,11 @@ +//! Keeps the GPU's copy of bake mode's visualization (high poly, cages, UV seams) in step with the session + +mod bake_scene_link; +mod cage_link; +mod cage_shell_key; +mod cage_upload; +mod reach_link; +mod shared_handle; + +pub use bake_scene_link::BakeSceneLink; +pub use cage_upload::CageUpload; diff --git a/crates/ui-egui/src/bake_scene/bake_scene_link.rs b/crates/ui-egui/src/bake_scene/bake_scene_link.rs new file mode 100644 index 00000000..7f4459c6 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -0,0 +1,213 @@ +use std::sync::Arc; + +use texturecraft_engine::Session; +use texturecraft_engine::geom::Mesh; +use texturecraft_render::BakeVisualization; + +use super::CageUpload; +use super::cage_link::CageLink; +use super::cage_shell_key::CageShellKey; +use super::reach_link::ReachLink; +use super::shared_handle::SharedHandle; +use crate::gpu::SceneSync; + +/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the UV seams +#[derive(Default)] +pub struct BakeSceneLink { + /// The high poly sent to the GPU and the id it was sent under (each new high poly gets the next one) + high: SharedHandle, + high_id: u64, + /// Whether the GPU has the high poly (a lost frame sends it again under the same id) + high_sent: bool, + cages: Vec>, + /// How many texture sets' cages the GPU was last told to keep + sent_cage_count: Option, + /// The low-poly mesh whose seams are uploaded + seams_mesh_id: Option, + next_topology: u64, + reach: ReachLink, +} + +impl BakeSceneLink { + /// Send everything again (the GPU lost what it was sent); the cage shells and the reach worked out on the CPU stay + pub fn resend(&mut self) { + self.high_sent = false; + self.sent_cage_count = None; + self.seams_mesh_id = None; + for link in self.cages.iter_mut().flatten() { + link.max_frontal = f32::NAN; + } + self.reach.resend(); + } + + /// Whether something is still being worked out off the UI thread + pub fn busy(&self) -> bool { + self.reach.busy() + } + + /// Add to `out` what the GPU needs to draw `visualization` this frame + pub fn sync(&mut self, session: &Session, visualization: Option, out: &mut SceneSync) { + let Some(visualization) = visualization else { return }; + + if visualization.high_poly { + let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone()); + let handle = SharedHandle::of(high.as_ref()); + if handle != self.high { + self.high = handle; + self.high_id += 1; + self.high_sent = false; + } + if !self.high_sent { + out.bake_high = Some((high, self.high_id)); + self.high_sent = true; + } + self.reach.sync(session, self.high_id, visualization.only_set, out); + } + + if visualization.uv_seams && self.seams_mesh_id != Some(session.mesh_id) { + self.seams_mesh_id = Some(session.mesh_id); + out.uv_seams = Some((session.mesh_id, session.mesh.uv_seam_edges())); + } + + if visualization.cage { + self.sync_cages(session, out); + } + } + + /// Rebuild the cages whose inputs changed and move the corners of those whose distance changed + fn sync_cages(&mut self, session: &Session, out: &mut SceneSync) { + let set_count = session.doc.project.texture_sets.len(); + if self.sent_cage_count != Some(set_count) { + out.bake_cage_count = Some(set_count); + self.sent_cage_count = Some(set_count); + } + self.cages.truncate(set_count); + self.cages.resize_with(set_count, || None); + + for (texture_set, link) in self.cages.iter_mut().enumerate() { + let (Some(key), Some(set)) = (CageShellKey::of(session, texture_set), session.doc.project.texture_sets.get(texture_set)) else { continue }; + + let max_frontal = set.bake.cage.max_frontal; + match link { + Some(link) if link.key == key => { + if link.max_frontal == max_frontal { + continue; + } + link.max_frontal = max_frontal; + } + _ => { + self.next_topology += 1; + let shell = session.bake_cage_inputs(texture_set).ok().flatten().and_then(|inputs| inputs.cage_shell().ok()).map(Arc::new); + *link = Some(CageLink { key, shell, topology: self.next_topology, max_frontal }); + } + } + + let Some(link) = link.as_ref() else { continue }; + + let upload = link.shell.as_ref().map(|shell| CageUpload { corners: shell.corners(max_frontal), shell: shell.clone() }); + out.bake_cages.push((texture_set, upload, link.topology)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None }; + + /// The sample project with a high poly a little outside its low poly + fn session() -> Session { + const HIGH_POLY_OFFSET: f32 = 0.02; + + let mut session = texturecraft_engine::sample_session(128, 128).unwrap(); + let low = session.mesh.clone(); + let mut obj = String::new(); + for (position, normal) in low.positions.iter().zip(&low.normals) { + let raised = *position + *normal * HIGH_POLY_OFFSET; + obj += &format!("v {} {} {}\n", raised.x, raised.y, raised.z); + } + for corners in low.indices.chunks(3) { + obj += &format!("f {} {} {}\n", corners[0] + 1, corners[1] + 1, corners[2] + 1); + } + session.add_high_poly_bytes("high.obj", obj.into_bytes()).unwrap(); + session + } + + fn sync(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> SceneSync { + let mut out = SceneSync::default(); + link.sync(session, Some(visualization), &mut out); + out + } + + /// Sync until the reach worked out on the worker thread colors the high poly; the share of vertices drawn red + fn red_share(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> f32 { + for _ in 0..2000 { + if let Some((_, missed)) = sync(link, session, visualization).bake_high_missed { + return missed.iter().sum::() / missed.len().max(1) as f32; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("the reach never arrived"); + } + + fn set_distances(session: &mut Session, max_frontal: f32) { + texturecraft_engine::execute(session, "bake.settings", &json!({"ts": "all", "maxFrontal": max_frontal})).unwrap(); + } + + #[test] + fn a_new_distance_moves_the_corners_and_new_settings_rebuild_the_cage() { + let (mut session, mut link) = (session(), BakeSceneLink::default()); + let first = sync(&mut link, &session, EVERYTHING); + assert!(first.bake_high.is_some() && first.uv_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len())); + let (_, Some(cage), topology) = first.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; + + let unchanged = sync(&mut link, &session, EVERYTHING); + assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.uv_seams.is_none(), "nothing changed, nothing is sent"); + + set_distances(&mut session, 0.03); + let moved = sync(&mut link, &session, EVERYTHING); + let (_, Some(moved_cage), moved_topology) = moved.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; + assert_eq!(moved_topology, topology, "a distance only moves the corners"); + assert_ne!(moved_cage.corners, cage.corners); + + texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap(); + let rebuilt = sync(&mut link, &session, EVERYTHING); + assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage"); + + link.resend(); + let resent = sync(&mut link, &session, EVERYTHING); + assert!(resent.bake_high.is_some() && resent.uv_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again"); + assert_eq!(resent.bake_cages.len(), rebuilt.bake_cages.len()); + assert_eq!(resent.bake_cages.first().unwrap().2, rebuilt.bake_cages.first().unwrap().2, "the cages are not rebuilt for a lost frame"); + assert_eq!(resent.bake_high.unwrap().1, first.bake_high.unwrap().1, "the high poly goes again under the same id"); + assert!(!link.busy(), "a lost frame doesn't work out the reach again"); + } + + #[test] + fn the_red_follows_the_distances_and_the_selected_set() { + let (mut session, mut link) = (session(), BakeSceneLink::default()); + set_distances(&mut session, 0.0); + let at_zero = red_share(&mut link, &session, EVERYTHING); + assert!(at_zero > 0.5, "at frontal 0 the high poly outside the low poly is red: {at_zero}"); + + set_distances(&mut session, 0.05); + let covered = red_share(&mut link, &session, EVERYTHING); + assert!(covered < at_zero / 10.0, "a cage past the high poly reaches it: {covered}"); + + set_distances(&mut session, 0.0); + let by_name = |session: &mut Session, low_suffix: &str| { + for set in &mut session.doc.project.texture_sets { + set.bake.high_poly.match_mode = texturecraft_engine::core::MeshMatchMode::ByMeshName; + set.bake.high_poly.low_suffix = low_suffix.into(); + } + }; + by_name(&mut session, "_no_such_suffix"); + let by_name_red = red_share(&mut link, &session, EVERYTHING); + assert!(by_name_red > 0.5, "matching by name and other suffixes works out the reach again: {by_name_red}"); + + let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..EVERYTHING }; + assert_eq!(red_share(&mut link, &session, no_set), 0.0, "sets left out by the filter color nothing"); + } +} diff --git a/crates/ui-egui/src/bake_scene/cage_link.rs b/crates/ui-egui/src/bake_scene/cage_link.rs new file mode 100644 index 00000000..855d9619 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_link.rs @@ -0,0 +1,16 @@ +use std::sync::Arc; + +use texturecraft_engine::bake::CageShell; + +use super::cage_shell_key::CageShellKey; + +/// A texture set's cage as the GPU has it +pub(super) struct CageLink { + pub(super) key: CageShellKey, + /// `None`: the set bakes without a high poly or its cage can't be built + pub(super) shell: Option>, + /// The renderer's name for the shell's corner order and edges + pub(super) topology: u64, + /// The max frontal distance the GPU's corners are at + pub(super) max_frontal: f32, +} diff --git a/crates/ui-egui/src/bake_scene/cage_shell_key.rs b/crates/ui-egui/src/bake_scene/cage_shell_key.rs new file mode 100644 index 00000000..44e17eca --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_shell_key.rs @@ -0,0 +1,47 @@ +use std::collections::BTreeMap; + +use texturecraft_engine::Session; +use texturecraft_engine::bake::BakePaintMap; +use texturecraft_engine::core::{BakePaintTarget, CageType, SkewSettings}; +use texturecraft_engine::geom::Mesh; + +use super::shared_handle::SharedHandle; + +/// Everything a texture set's cage shell is built from except the distances, which only move its corners +#[derive(Clone, Debug, PartialEq)] +pub(super) struct CageShellKey { + mesh_id: u64, + high: SharedHandle, + cage_file: SharedHandle, + material: usize, + uv_tiles: Vec, + tile_resolutions: BTreeMap, + cage_kind: CageType, + relative_to_bounding_box: bool, + average_normals: bool, + use_low_as_high: bool, + skew: SkewSettings, + /// The painted skew and cage maps + paint: [SharedHandle; 2], +} + +impl CageShellKey { + pub(super) fn of(session: &Session, texture_set: usize) -> Option { + let set = session.doc.project.texture_sets.get(texture_set)?; + let paint = |target| SharedHandle::of(session.doc.bake_paint.get(&(texture_set, target))); + Some(CageShellKey { + mesh_id: session.mesh_id, + high: SharedHandle::of(session.bake_meshes.merged_high().map(|high| &high.mesh)), + cage_file: SharedHandle::of(session.bake_meshes.cage.as_ref().map(|cage| &cage.mesh)), + material: set.material, + uv_tiles: set.uv_tiles.clone(), + tile_resolutions: set.tile_resolutions.clone(), + cage_kind: set.bake.cage.kind, + relative_to_bounding_box: set.bake.cage.relative_to_bounding_box, + average_normals: set.bake.cage.average_normals, + use_low_as_high: set.bake.high_poly.use_low_as_high, + skew: set.bake.skew, + paint: [paint(BakePaintTarget::Skew), paint(BakePaintTarget::Cage)], + }) + } +} diff --git a/crates/ui-egui/src/bake_scene/cage_upload.rs b/crates/ui-egui/src/bake_scene/cage_upload.rs new file mode 100644 index 00000000..81951645 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_upload.rs @@ -0,0 +1,10 @@ +use std::sync::Arc; + +use texturecraft_engine::bake::CageShell; +use texturecraft_engine::geom::glam::Vec3; + +/// A texture set's cage for the GPU: its corners at the current distance and the shell they come from +pub struct CageUpload { + pub corners: Vec, + pub shell: Arc, +} diff --git a/crates/ui-egui/src/bake_scene/reach_link.rs b/crates/ui-egui/src/bake_scene/reach_link.rs new file mode 100644 index 00000000..45527522 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/reach_link.rs @@ -0,0 +1,100 @@ +use std::sync::mpsc::{Receiver, TryRecvError}; + +use rayon::prelude::*; +use texturecraft_engine::Session; +use texturecraft_engine::bake::HighPolyReach; +use texturecraft_engine::core::HighPolySettings; + +use super::cage_shell_key::CageShellKey; +use crate::gpu::SceneSync; + +/// Each set's (max frontal, max rear) and the selected-set filter +type ShownDistances = (Vec<(f32, f32)>, Option); + +/// The red on the high poly: each texture set's ray reach, worked out on a worker thread, and the distances the GPU's colors show +#[derive(Default)] +pub(super) struct ReachLink { + /// Each set's ray inputs and high-poly settings (backfaces, name matching), and the id of the high poly, the reach was started for + keys: Vec>, + high_id: u64, + job: Option>>>, + reach: Vec>, + /// Each set's (max frontal, max rear) and the selected-set filter the GPU's colors are for + shown: Option, +} + +impl ReachLink { + /// Whether a reach is being worked out (the view must keep drawing to pick it up) + pub(super) fn busy(&self) -> bool { + self.job.is_some() + } + + /// Send the colors again (the GPU lost what it was sent); the reach itself stays + pub(super) fn resend(&mut self) { + self.shown = None; + } + + /// Start a new reach when the high poly (sent under `high_id`) or a set's inputs changed, and color the high poly when the reach or the distances changed + pub(super) fn sync(&mut self, session: &Session, high_id: u64, only_set: Option, out: &mut SceneSync) { + let set_count = session.doc.project.texture_sets.len(); + let keys: Vec> = session + .doc + .project + .texture_sets + .iter() + .enumerate() + .map(|(texture_set, set)| Some((CageShellKey::of(session, texture_set)?, set.bake.high_poly.clone()))) + .collect(); + if keys != self.keys || high_id != self.high_id { + let inputs: Vec<_> = (0..set_count).map(|texture_set| session.bake_cage_inputs(texture_set).ok().flatten()).collect(); + self.job = Some(crate::spawn_worker("texturecraft-bake-reach", move || { + inputs.iter().map(|inputs| inputs.as_ref().and_then(|inputs| inputs.high_poly_reach().ok())).collect() + })); + (self.keys, self.high_id) = (keys, high_id); + } + + if let Some(job) = &self.job { + match job.try_recv() { + Ok(reach) => { + self.reach = reach; + self.shown = None; + self.job = None; + } + Err(TryRecvError::Disconnected) => self.job = None, + Err(TryRecvError::Empty) => {} + } + } + + // Colors wait for the reach being worked out: the old ones stay until it arrives + if self.job.is_some() { + return; + } + + let distances: Vec<(f32, f32)> = session.doc.project.texture_sets.iter().map(|set| (set.bake.cage.max_frontal, set.bake.cage.max_rear)).collect(); + let shown = (distances, only_set); + if self.shown.as_ref() == Some(&shown) { + return; + } + + let Some(vertex_count) = session.bake_meshes.merged_high().map(|high| high.mesh.positions.len()) else { return }; + + // Each vertex is its nearest set's: other sets, and a set left out by the selected-set filter, never color it + let sets: Vec<(&HighPolyReach, f32, f32)> = self + .reach + .iter() + .zip(&shown.0) + .enumerate() + .filter(|(texture_set, _)| only_set.is_none_or(|only| only == *texture_set)) + .filter_map(|(_, (reach, &(max_frontal, max_rear)))| Some((reach.as_ref()?, max_frontal, max_rear))) + .collect(); + let missed: Vec = (0..vertex_count) + .into_par_iter() + .map(|vertex| { + let missed = sets.iter().find_map(|(reach, max_frontal, max_rear)| reach.missed(vertex, *max_frontal, *max_rear)); + f32::from(u8::from(missed.unwrap_or(false))) + }) + .collect(); + out.bake_high_missed = Some((self.high_id, missed)); + self.shown = Some(shown); + } +} diff --git a/crates/ui-egui/src/bake_scene/shared_handle.rs b/crates/ui-egui/src/bake_scene/shared_handle.rs new file mode 100644 index 00000000..15ceb1d8 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/shared_handle.rs @@ -0,0 +1,32 @@ +use std::sync::{Arc, Weak}; + +/// Which shared value a key refers to, without keeping the value alive; the held `Weak` keeps its address from being reused, so a new value never passes for it +#[derive(Debug)] +pub(super) struct SharedHandle(Option>); + +impl SharedHandle { + pub(super) fn of(value: Option<&Arc>) -> SharedHandle { + SharedHandle(value.map(Arc::downgrade)) + } +} + +impl Clone for SharedHandle { + fn clone(&self) -> Self { + SharedHandle(self.0.clone()) + } +} + +impl Default for SharedHandle { + fn default() -> Self { + SharedHandle(None) + } +} + +impl PartialEq for SharedHandle { + fn eq(&self, other: &Self) -> bool { + match (&self.0, &other.0) { + (Some(this), Some(other)) => Weak::ptr_eq(this, other), + (this, other) => this.is_none() && other.is_none(), + } + } +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index c6695b34..6bce1312 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -11,7 +11,9 @@ use texturecraft_engine::Session; use texturecraft_engine::compose::{DisplayKind, ImageRes, tile_bytes}; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::Mesh; -use texturecraft_render::{Frame, Renderer, wgpu}; +use texturecraft_render::{BakeVisualization, Frame, Renderer, wgpu}; + +use crate::bake_scene::{BakeSceneLink, CageUpload}; /// Content shown through the aux texture. #[derive(Clone, Copy, Debug, PartialEq)] @@ -25,6 +27,9 @@ pub enum AuxView { /// A texture set's texels across and down, and its mesh material. pub type SetLayout = ((u32, u32), usize); +/// The low poly's UV seam edges (vertex pairs) per material +pub type UvSeamEdges = Vec>; + /// What the renderer must catch up with before drawing. #[derive(Default)] pub struct SceneSync { @@ -36,6 +41,16 @@ pub struct SceneSync { pub env: Option<(String, Option>)>, pub tiles: Vec<(usize, DisplayKind, u32, u32, Vec)>, pub aux: Vec<(usize, u32, Vec)>, + /// Bake mode's high poly (`None` removes it) and the id it is sent under + pub bake_high: Option<(Option>, u64)>, + /// Which vertices of the high poly (by its id) the bake's rays miss (1) or reach (0) + pub bake_high_missed: Option<(u64, Vec)>, + /// Changed cages: texture set, the cage or `None` to remove it, its topology + pub bake_cages: Vec<(usize, Option, u64)>, + /// Texture sets left after some were removed: their cages go too + pub bake_cage_count: Option, + /// The low poly's UV seams per material, for mesh id + pub uv_seams: Option<(u64, UvSeamEdges)>, } /// Lives in egui's callback resources. @@ -78,6 +93,7 @@ pub struct GpuLink { pub adapter: String, /// Most tiles waiting to be composited since compositing last caught up (progress). composite_total: usize, + bake_scene: BakeSceneLink, } /// Compositing time per frame: a full recomposite of a large texture set spreads over frames. @@ -124,6 +140,7 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { aux: BTreeMap::new(), adapter: format!("{} ({:?})", info.name, info.backend), composite_total: 0, + bake_scene: BakeSceneLink::default(), } } @@ -133,132 +150,158 @@ impl GpuLink { std::mem::take(&mut *self.reports.lock().unwrap_or_else(PoisonError::into_inner)) } - /// Collect everything the GPU needs this frame (runs the compositor first). + /// Whether bake mode's visualization is still being worked out off the UI thread + pub fn bake_busy(&self) -> bool { + self.bake_scene.busy() + } + /// Compositing progress (0..1) while tiles wait to be composited. pub fn composite_progress(&self, s: &Session) -> Option { let pending = s.pending_tiles(); (pending > 0 && self.composite_total > 0).then(|| 1.0 - pending as f32 / self.composite_total as f32) } - /// `spent_ms`: time this frame already took before the sync. - pub fn sync(&mut self, s: &mut Session, aux_map: Option, shift: u32, spent_ms: f64) -> SceneSync { - let start = crate::now_ms(); + /// Collect everything the GPU needs this frame, running the compositor first: `bake` is what bake mode's 3D view draws besides the low poly, `spent_ms` the time this frame already took + pub fn sync(&mut self, session: &mut Session, aux_map: Option, bake: Option, shift: u32, spent_ms: f64) -> SceneSync { + let start_ms = crate::now_ms(); let mut queued = 0usize; - let left = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start) - queued as f64 * UPLOAD_MS_PER_TILE; - let pending = s.pending_tiles(); + let time_left_ms = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE; + let pending = session.pending_tiles(); self.composite_total = if pending == 0 { 0 } else { self.composite_total.max(pending) }; - s.update_for(COMPOSITE_BUDGET_MS.min(left(0)).max(MIN_SLICE_MS), crate::now_ms); + session.update_for(COMPOSITE_BUDGET_MS.min(time_left_ms(0)).max(MIN_SLICE_MS), crate::now_ms); + let mut out = SceneSync::default(); if self.lost.swap(false, Ordering::AcqRel) { self.mesh_id = 0; self.sets.clear(); self.env = Default::default(); + self.bake_scene.resend(); self.reset.store(true, Ordering::Release); } - if self.mesh_id != s.mesh_id { - out.mesh = Some((s.mesh.clone(), s.mesh_id)); - self.mesh_id = s.mesh_id; + + if self.mesh_id != session.mesh_id { + out.mesh = Some((session.mesh.clone(), session.mesh_id)); + self.mesh_id = session.mesh_id; self.aux.clear(); } - let sets: Vec = s.doc.project.texture_sets.iter().map(|t| (t.size(), t.material)).collect(); + + let sets: Vec = session.doc.project.texture_sets.iter().map(|texture_set| (texture_set.size(), texture_set.material)).collect(); if sets != self.sets || shift != self.shift || out.mesh.is_some() { - out.sets = Some((sets.clone(), s.mesh.materials.len().max(1), shift)); + out.sets = Some((sets.clone(), session.mesh.materials.len().max(1), shift)); self.sets = sets; self.shift = shift; } - let d = &s.doc.project.display; - let image = d.environment_resource().and_then(|n| s.images.get(n)); - let ptr = image.map_or(0, |i| Arc::as_ptr(i) as usize); - if self.env.0 != d.environment || self.env.1 != ptr { - self.env = (d.environment.clone(), ptr); - out.env = Some((d.environment.clone(), image.cloned())); + + let display = &session.doc.project.display; + let image = display.environment_resource().and_then(|name| session.images.get(name)); + let image_identity = image.map_or(0, |image| Arc::as_ptr(image) as usize); + if self.env.0 != display.environment || self.env.1 != image_identity { + self.env = (display.environment.clone(), image_identity); + out.env = Some((display.environment.clone(), image.cloned())); } + if self.reset.swap(false, Ordering::AcqRel) { - for c in &mut s.caches { - c.upload.extend(texturecraft_engine::compose::all_tiles(c.size.0, c.size.1)); + for cache in &mut session.caches { + cache.upload.extend(texturecraft_engine::compose::all_tiles(cache.size.0, cache.size.1)); } self.aux.clear(); } - for ts in 0..s.caches.len() { - let tiles = s.take_uploads(ts); + + for texture_set in 0..session.caches.len() { + let tiles = session.take_uploads(texture_set); if tiles.is_empty() { continue; } + let mut done = 0; - if let Some(cache) = s.caches.get(ts) { + if let Some(cache) = session.caches.get(texture_set) { let empty = Default::default(); - let baked = s.doc.baked.get(&ts).unwrap_or(&empty); - let comp = &cache.composite; - // In chunks while the frame has time (at least one chunk); the rest waits. + let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty); + let composite = &cache.composite; + // In chunks while the frame has time (at least one chunk); the rest waits for chunk in tiles.chunks(UPLOAD_CHUNK) { let bytes: Vec<_> = chunk .par_iter() - .flat_map_iter(|&(tx, ty)| DisplayKind::ALL.into_iter().map(move |k| (k, tx, ty))) - .map(|(k, tx, ty)| (ts, k, tx, ty, tile_bytes(comp, baked, k, tx, ty))) + .flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.into_iter().map(move |kind| (kind, tile_x, tile_y))) + .map(|(kind, tile_x, tile_y)| (texture_set, kind, tile_x, tile_y, tile_bytes(composite, baked, kind, tile_x, tile_y))) .collect(); queued += bytes.len(); out.tiles.extend(bytes); done += chunk.len(); - if left(queued) < MIN_SLICE_MS { + if time_left_ms(queued) < MIN_SLICE_MS { break; } } } - if let (Some(rest), Some(cache)) = (tiles.get(done..), s.caches.get_mut(ts)) { + if let (Some(rest), Some(cache)) = (tiles.get(done..), session.caches.get_mut(texture_set)) { cache.upload.extend(rest.iter().copied()); } } + match aux_map { - Some(AuxView::MeshMap(m)) => { - for ts in 0..s.caches.len() { - let rev = s.doc.baked.get(&ts).and_then(|b| b.maps.get(&m)).map(|d| Arc::as_ptr(d) as u64).unwrap_or(0); - let key = (format!("{m:?}"), rev); - if self.aux.get(&ts) == Some(&key) { + Some(AuxView::MeshMap(map)) => { + for texture_set in 0..session.caches.len() { + let revision = session.doc.baked.get(&texture_set).and_then(|baked| baked.maps.get(&map)).map(|data| Arc::as_ptr(data) as u64).unwrap_or(0); + let key = (format!("{map:?}"), revision); + if self.aux.get(&texture_set) == Some(&key) { continue; } - let Some(cache) = s.caches.get(ts) else { continue }; + let Some(cache) = session.caches.get(texture_set) else { continue }; - let res = texturecraft_render::aux_size(cache.size); + let resolution = texturecraft_render::aux_size(cache.size); out.aux.push(( - ts, - res, - texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res, cache.size, &cache.composite.block_scales), + texture_set, + resolution, + texturecraft_render::mesh_maps::mesh_map_rgba( + session.doc.baked.get(&texture_set), + map, + resolution, + cache.size, + &cache.composite.block_scales, + ), )); - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } Some(AuxView::Mask(id)) => { - if let Some((ts, _, _)) = s.doc.project.locate(id) { - let key = (format!("mask{}", id.0), s.revision); - if self.aux.get(&ts) != Some(&key) && !s.stroke_active() { - let res = s.caches.get(ts).map_or(1024, |c| texturecraft_render::aux_size(c.size)); - if let Some(rgba) = s.mask_view_rgba(id, res) { - out.aux.push((ts, res, rgba)); + if let Some((texture_set, _, _)) = session.doc.project.locate(id) { + let key = (format!("mask{}", id.0), session.revision); + if self.aux.get(&texture_set) != Some(&key) && !session.stroke_active() { + let resolution = + session.caches.get(texture_set).map_or(MASK_VIEW_FALLBACK_RESOLUTION, |cache| texturecraft_render::aux_size(cache.size)); + if let Some(rgba) = session.mask_view_rgba(id, resolution) { + out.aux.push((texture_set, resolution, rgba)); } - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } } Some(AuxView::QuickMask) => { - for ts in 0..s.caches.len() { - let Some(cache) = s.caches.get(ts) else { continue }; - let key = (format!("quickmask{}", s.quick_mask.revision), cache.revision); - if self.aux.get(&ts) == Some(&key) { + for texture_set in 0..session.caches.len() { + let Some(cache) = session.caches.get(texture_set) else { continue }; + + let key = (format!("quickmask{}", session.quick_mask.revision), cache.revision); + if self.aux.get(&texture_set) == Some(&key) { continue; } - let res = texturecraft_render::aux_size(cache.size); - if let Some(rgba) = s.quick_mask_rgba(ts, res) { - out.aux.push((ts, res, rgba)); + let resolution = texturecraft_render::aux_size(cache.size); + if let Some(rgba) = session.quick_mask_rgba(texture_set, resolution) { + out.aux.push((texture_set, resolution, rgba)); } - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } None => {} } + + self.bake_scene.sync(session, bake, &mut out); out } } +/// Mask view resolution for a texture set without a composite cache +const MASK_VIEW_FALLBACK_RESOLUTION: u32 = 1024; + /// Paint callback for one view. pub struct ViewCallback { pub frame: Frame, @@ -295,39 +338,58 @@ impl CallbackTrait for ViewCallback { if let Some((mesh, id)) = &sync.mesh { gpu.renderer.set_mesh(device, queue, mesh, *id); } - if let Some((sets, mats, shift)) = &sync.sets { + if let Some((sets, material_count, shift)) = &sync.sets { gpu.renderer.set_display_shift(*shift); - let reset = gpu.renderer.set_texture_sets(device, queue, sets, *mats); + let reset = gpu.renderer.set_texture_sets(device, queue, sets, *material_count); if !reset.is_empty() { gpu.reset.store(true, Ordering::Release); } } - for (ts, k, tx, ty, bytes) in &sync.tiles { - gpu.renderer.upload_tile(device, queue, *ts, *k, *tx, *ty, bytes); + for (texture_set, kind, tile_x, tile_y, bytes) in &sync.tiles { + gpu.renderer.upload_tile(device, queue, *texture_set, *kind, *tile_x, *tile_y, bytes); } - for (ts, size, bytes) in &sync.aux { - gpu.renderer.upload_aux(device, queue, *ts, *size, bytes); + for (texture_set, size, bytes) in &sync.aux { + gpu.renderer.upload_aux(device, queue, *texture_set, *size, bytes); + } + if let Some((high, id)) = &sync.bake_high { + gpu.renderer.set_bake_high(device, queue, high.as_deref(), *id); + } + if let Some((id, missed)) = &sync.bake_high_missed { + gpu.renderer.set_bake_high_missed(queue, *id, missed); + } + if let Some(count) = sync.bake_cage_count { + gpu.renderer.truncate_bake_cages(count); + } + for (texture_set, cage, topology) in &sync.bake_cages { + let cage = cage.as_ref().map(|upload| (upload.corners.as_slice(), upload.shell.edges.as_slice())); + gpu.renderer.set_bake_cage(device, queue, *texture_set, cage, *topology); + } + if let Some((mesh_id, seams)) = &sync.uv_seams { + gpu.renderer.set_uv_seams(device, queue, *mesh_id, seams); } } - // Also installs (or rejects) full-size textures WebGPU answered for since last frame. + + // Also installs (or rejects) full-size textures WebGPU answered for since last frame gpu.renderer.prepare(device, queue, encoder, &self.frame); let failed = gpu.renderer.take_memory_failures(); if !failed.is_empty() { - let mut r = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); - for ts in failed { - if !r.memory.contains(&ts) { - r.memory.push(ts); + let mut reports = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); + for texture_set in failed { + if !reports.memory.contains(&texture_set) { + reports.memory.push(texture_set); } } - // This frame's report drain already ran: the next frame shows the toast. + // This frame's report drain already ran: the next frame shows the toast gpu.ctx.request_repaint(); } if gpu.renderer.awaiting_gpu() { gpu.ctx.request_repaint(); } - let ppp = screen.pixels_per_point; - let r = self.rect; - gpu.renderer.set_blit_rect(queue, self.frame.view_id, [r.min.x * ppp, r.min.y * ppp, r.width() * ppp, r.height() * ppp], screen.size_in_pixels); + + let pixels_per_point = screen.pixels_per_point; + let rect = self.rect; + let blit_rect = [rect.min.x * pixels_per_point, rect.min.y * pixels_per_point, rect.width() * pixels_per_point, rect.height() * pixels_per_point]; + gpu.renderer.set_blit_rect(queue, self.frame.view_id, blit_rect, screen.size_in_pixels); Vec::new() } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..5487c415 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1035,4 +1035,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Baking Visualization", "تصور الخبز"), + ("Show for Selected Texture Set Only", "العرض لمجموعة الخامات المحددة فقط"), + ("High Definition Mesh (HP)", "المجسم عالي الدقة (HP)"), + ("UV Seams", "فواصل UV"), + ("Project Mesh (LP)", "مجسم الإسقاط (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..ac1c709d 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1078,4 +1078,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Auflösungsüberschreibung entfernen"), ("Texture set resolution", "Auflösung des Textursets"), ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ("Baking Visualization", "Bake-Visualisierung"), + ("Show for Selected Texture Set Only", "Nur für das ausgewählte Texturset anzeigen"), + ("High Definition Mesh (HP)", "High-Poly-Mesh (HP)"), + ("UV Seams", "UV-Nähte"), + ("Project Mesh (LP)", "Projektions-Mesh (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..07b0be27 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1063,4 +1063,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Quitar resolución personalizada"), ("Texture set resolution", "Resolución del conjunto de texturas"), ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ("Baking Visualization", "Visualización del horneado"), + ("Show for Selected Texture Set Only", "Mostrar solo para el conjunto de texturas seleccionado"), + ("High Definition Mesh (HP)", "Malla de alta resolución (HP)"), + ("UV Seams", "Costuras UV"), + ("Project Mesh (LP)", "Malla de proyección (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..0f5288c9 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1087,4 +1087,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Supprimer la résolution personnalisée"), ("Texture set resolution", "Résolution de l'ensemble de textures"), ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ("Baking Visualization", "Visualisation du baking"), + ("Show for Selected Texture Set Only", "Afficher uniquement pour l'ensemble de textures sélectionné"), + ("High Definition Mesh (HP)", "Maillage haute définition (HP)"), + ("UV Seams", "Coutures UV"), + ("Project Mesh (LP)", "Maillage de projection (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..e3956a8c 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1072,4 +1072,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Rimuovi risoluzione personalizzata"), ("Texture set resolution", "Risoluzione del set di texture"), ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ("Baking Visualization", "Visualizzazione del baking"), + ("Show for Selected Texture Set Only", "Mostra solo per il set di texture selezionato"), + ("High Definition Mesh (HP)", "Mesh ad alta risoluzione (HP)"), + ("UV Seams", "Cuciture UV"), + ("Project Mesh (LP)", "Mesh di proiezione (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..089e77e4 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1057,4 +1057,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Baking Visualization", "ベイクの可視化"), + ("Show for Selected Texture Set Only", "選択したテクスチャセットのみ表示"), + ("High Definition Mesh (HP)", "ハイポリメッシュ (HP)"), + ("UV Seams", "UVシーム"), + ("Project Mesh (LP)", "投影メッシュ (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..726e1c35 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1045,4 +1045,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Baking Visualization", "베이크 시각화"), + ("Show for Selected Texture Set Only", "선택한 텍스처 세트만 표시"), + ("High Definition Mesh (HP)", "하이 폴리 메시 (HP)"), + ("UV Seams", "UV 심"), + ("Project Mesh (LP)", "투영 메시 (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..607c0c49 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1060,4 +1060,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Remover resolução personalizada"), ("Texture set resolution", "Resolução do conjunto de texturas"), ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ("Baking Visualization", "Visualização do bake"), + ("Show for Selected Texture Set Only", "Mostrar apenas para o conjunto de texturas selecionado"), + ("High Definition Mesh (HP)", "Malha de alta resolução (HP)"), + ("UV Seams", "Costuras UV"), + ("Project Mesh (LP)", "Malha de projeção (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..5b47bd31 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1003,4 +1003,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Baking Visualization", "烘焙可视化"), + ("Show for Selected Texture Set Only", "仅显示所选纹理集"), + ("High Definition Mesh (HP)", "高模网格 (HP)"), + ("UV Seams", "UV 接缝"), + ("Project Mesh (LP)", "投射网格 (LP)"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..bd7591fc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -8,6 +8,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod bake_mode; +mod bake_scene; pub mod control; pub mod dock; pub mod docking; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..94958f61 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -296,6 +296,9 @@ pub struct UiState { /// The brush that paints the skew correction map in the 2D view of bake mode. #[serde(default)] pub bake_paint_brush: crate::bake_mode::BakePaintBrush, + /// What bake mode's 3D view draws besides the low poly (the Baking Visualization panel) + #[serde(default)] + pub bake_visualization: crate::bake_mode::BakeVisualizationToggles, } impl UiState { @@ -365,6 +368,7 @@ impl Default for UiState { recent: Vec::new(), keymap: Keymap::new(), bake_paint_brush: crate::bake_mode::BakePaintBrush::default(), + bake_visualization: crate::bake_mode::BakeVisualizationToggles::default(), } } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..82bd0258 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -296,30 +296,43 @@ fn frame_size_in_pixels(ui: &Ui, rect: Rect) -> [u32; 2] { } fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, frame: Frame, sync: &mut PendingSync) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); + let bake = bake_visualization(app); let scene = match (sync.0.take(), app.gpu.as_mut()) { - (Some(aux), Some(g)) => { - let t0 = crate::now_ms(); - let scene = g.sync(&mut app.session, aux, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); - let reports = g.take_reports(); - app.profiler.sync_ms += (crate::now_ms() - t0) as f32; + (Some(aux), Some(gpu_link)) => { + let sync_start_ms = crate::now_ms(); + let scene = gpu_link.sync(&mut app.session, aux, bake, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); + let reports = gpu_link.take_reports(); + app.profiler.sync_ms += (crate::now_ms() - sync_start_ms) as f32; gpu_report_toasts(app, reports); - // Display tiles left for later frames (the frame budget ran out). - if app.session.caches.iter().any(|c| !c.upload.is_empty()) { + + // Display tiles left for later frames (the frame budget ran out), or the bake visualization still being worked out + if app.session.caches.iter().any(|cache| !cache.upload.is_empty()) || app.gpu.as_ref().is_some_and(crate::gpu::GpuLink::bake_busy) { ui.ctx().request_repaint(); } Some(scene) } _ => None, }; + let Some(gpu) = &app.gpu else { - ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, tr("No GPU renderer available"), egui::FontId::proportional(14.0), tk.viewport_text); + ui.painter().text( + rect.center(), + egui::Align2::CENTER_CENTER, + tr("No GPU renderer available"), + egui::FontId::proportional(NO_GPU_TEXT_SIZE), + tokens.viewport_text, + ); return; }; - let cb = ViewCallback { frame, sync: Mutex::new(scene), rect, lost: gpu.lost.clone() }; - ui.painter().add(eframe::egui_wgpu::Callback::new_paint_callback(rect, cb)); + + let callback = ViewCallback { frame, sync: Mutex::new(scene), rect, lost: gpu.lost.clone() }; + ui.painter().add(eframe::egui_wgpu::Callback::new_paint_callback(rect, callback)); } +/// Text size of the notice a view shows without a GPU renderer +const NO_GPU_TEXT_SIZE: f32 = 14.0; + /// Width of the camera and view pickers centred at the top of a view const VIEW_HEADER_WIDTH: f32 = 300.0; @@ -617,7 +630,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin size: frame_size_in_pixels(ui, rect), kind: ViewKind::Scene, camera: app.session.camera, - shade: Shade { highlight: drop_highlight(app, ui, &response), ..shade(app) }, + shade: Shade { highlight: drop_highlight(app, ui, &response), bake: bake_visualization(app), ..shade(app) }, visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); @@ -658,17 +671,30 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin brush_readout(app, ui, &response, adjusting); if app.session.quick_mask.editing { ui.painter_at(rect).text( - rect.left_top() + vec2(12.0, 40.0), + rect.left_top() + QUICK_MASK_NOTICE_OFFSET, egui::Align2::LEFT_TOP, tr("Editing quick mask: paint where painting is allowed (U to finish)"), - egui::FontId::proportional(12.0), - Color32::from_rgb(0xe8, 0x6a, 0x6a), + egui::FontId::proportional(QUICK_MASK_NOTICE_TEXT_SIZE), + QUICK_MASK_NOTICE_COLOR, ); } + if app.ui.mode == crate::state::Mode::Baking { + crate::bake_mode::bake_visualization_panel(app, ui, rect); + } view_header(app, ui, rect, "v3d"); axis_gizmo(ui, rect, app, false); } +/// Where the quick-mask editing notice sits from the 3D view's top-left corner, its text size and its warning red +const QUICK_MASK_NOTICE_OFFSET: egui::Vec2 = vec2(12.0, 40.0); +const QUICK_MASK_NOTICE_TEXT_SIZE: f32 = 12.0; +const QUICK_MASK_NOTICE_COLOR: Color32 = Color32::from_rgb(0xe8, 0x6a, 0x6a); + +/// What bake mode's 3D view draws besides the low poly (nothing in the other modes) +fn bake_visualization(app: &TextureCraftApp) -> Option { + (app.ui.mode == crate::state::Mode::Baking).then(|| app.ui.bake_visualization.visualization(app.session.ts())).flatten() +} + /// What a drag on the selected decal's frame does. #[derive(Clone, Copy, Debug, PartialEq)] enum DecalGrab { From ca19e714a0cf76fd809f9abc47ef8cdc8d3d86e6 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 08:51:56 +0000 Subject: [PATCH 40/73] Filter picker: swap a filter's type from its Properties slot effect.set takes filter: to swap a filter effect's type in place, keeping its place, blending, opacity and visibility (one undo step). A reusable resource_picker shows grouped, searchable shelf tiles at a slot; the filter slot uses it, and Add filter adds a neutral filter. --- crates/engine/src/filter_lib.rs | 7 ++ crates/engine/src/mask_cmds.rs | 96 +++++++++++----- crates/engine/tests/filter_swap.rs | 94 +++++++++++++++ crates/ui-egui/src/dock.rs | 126 ++++++++++----------- crates/ui-egui/src/filter_slot.rs | 83 ++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 2 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/es.rs | 2 + crates/ui-egui/src/i18n/fr.rs | 2 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/ko.rs | 2 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/zh_hans.rs | 2 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/menus.rs | 8 +- crates/ui-egui/src/resource_picker.rs | 126 +++++++++++++++++++++ crates/ui-egui/src/resource_picker_item.rs | 9 ++ crates/ui-egui/src/shelf.rs | 10 +- crates/ui-egui/tests/filter_picker.rs | 81 +++++++++++++ 20 files changed, 562 insertions(+), 99 deletions(-) create mode 100644 crates/engine/tests/filter_swap.rs create mode 100644 crates/ui-egui/src/filter_slot.rs create mode 100644 crates/ui-egui/src/resource_picker.rs create mode 100644 crates/ui-egui/src/resource_picker_item.rs create mode 100644 crates/ui-egui/tests/filter_picker.rs diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index f3168c9d..0f0fd952 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -19,6 +19,13 @@ pub struct FilterDef { pub mask: bool, } +impl FilterDef { + /// Whether it builds a filter effect (levels and material finishes are effect types of their own) + pub fn is_filter_effect(&self) -> bool { + matches!(build(self.id, &Value::Null), Ok(EffectKind::Filter(_))) + } +} + const fn def(id: &'static str, label: &'static str, group: &'static str, mask: bool) -> FilterDef { FilterDef { id, label, group, mask } } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 2656bd15..bd545fbc 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity), level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", has_layer, set ), @@ -413,55 +413,76 @@ fn histogram(s: &mut Session, p: &Value) -> Result { Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) }) } +/// Edits effect `effect`: visibility, blending, name, its kind's parameters, or a filter's type fn set(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(s, p, "effect.set")?; - let blend = blend_param("effect.set", p, "blend")?; - // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone - // re-targets the current one. - let anchor = match s.doc.project.effect(eid) { + const CMD: &str = "effect.set"; + let effect = effect_id(s, p, CMD)?; + let blend = blend_param(CMD, p, "blend")?; + + // `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one + let anchor = match s.doc.project.effect(effect) { Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => { let (current, channel) = match source { Source::Anchor { anchor, channel } => (Some(*anchor), *channel), _ => (None, Channel::Height), }; - let channel_param = channel_param("effect.set", p, "anchorChannel")?; + let channel_param = channel_param(CMD, p, "anchorChannel")?; match u64p(p, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) { - Some(a) => Some(anchor_source(s, "effect.set", owner, a, channel_param.unwrap_or(channel))?), + Some(anchor) => Some(anchor_source(s, CMD, owner, anchor, channel_param.unwrap_or(channel))?), None => None, } } _ => None, }; + + let swapped = match strp(p, "filter") { + Some(filter) => Some(swapped_filter(s, effect, filter, p)?), + None => None, + }; + let swaps_filter = swapped.is_some(); + s.edit("Edit effect", |s| { - let e = s.doc.project.effect_mut(eid).ok_or_else(|| bad("effect.set", format!("no effect {}", eid.0)))?; - if let Some(v) = boolp(p, "visible") { - e.visible = v; + let edited = s.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if let Some((kind, label)) = swapped { + if let EffectKind::Filter(old) = &edited.kind + && edited.name == old.label() + { + edited.name = label.to_string(); + } + edited.kind = kind; } - if let Some(b) = blend { - e.blend = b; + + if let Some(visible) = boolp(p, "visible") { + edited.visible = visible; } - if let Some(o) = f32p(p, "opacity") { - e.opacity = o.clamp(0.0, 1.0); + if let Some(blend) = blend { + edited.blend = blend; } - if let Some(n) = name_param(p) { - e.name = n.to_string(); + if let Some(opacity) = f32p(p, "opacity") { + edited.opacity = opacity.clamp(0.0, 1.0); } - match &mut e.kind { - EffectKind::Generator(g) => generator_from(p, g), - EffectKind::Levels(l) => levels_from(p, l), - EffectKind::Filter(f) => crate::filter_lib::apply(p, f, "effect.set")?, + if let Some(name) = name_param(p) { + edited.name = name.to_string(); + } + + match &mut edited.kind { + EffectKind::Generator(generator) => generator_from(p, generator), + EffectKind::Levels(levels) => levels_from(p, levels), + // The swapped filter was built with the parameters already + EffectKind::Filter(_) if swaps_filter => {} + EffectKind::Filter(filter) => crate::filter_lib::apply(p, filter, CMD)?, EffectKind::Fill { source, .. } => { - if let Some(a) = anchor { - *source = a; - } else if let Some(x) = f32p(p, "value") + if let Some(anchor) = anchor { + *source = anchor; + } else if let Some(value) = f32p(p, "value") && matches!(source, Source::Uniform(_) | Source::Anchor { .. }) { - *source = Source::Uniform([x.clamp(0.0, 1.0); 3]); + *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } } EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => { - if let Some(x) = f32p(p, "tolerance") { - *tolerance = x.clamp(0.0, 1.0); + if let Some(value) = f32p(p, "tolerance") { + *tolerance = value.clamp(0.0, 1.0); } } _ => {} @@ -471,6 +492,27 @@ fn set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Filter `id` built with `p` and its label, to replace filter effect `effect` +fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(EffectKind, &'static str)> { + const CMD: &str = "effect.set"; + let (owner, current) = s.doc.project.effect(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if !matches!(current.kind, EffectKind::Filter(_)) { + return Err(bad(CMD, format!("`filter` changes filter effects only, not {}", current.kind.name().to_ascii_lowercase()))); + } + + let def = crate::filter_lib::find(id).ok_or_else(|| bad(CMD, format!("unknown filter `{id}` (see filter.list)")))?; + if !def.is_filter_effect() { + return Err(bad(CMD, format!("{} is its own effect type: add it with effect.add.filter", def.label))); + } + + let mask = s.doc.project.layer(owner)?.mask.as_ref(); + let on_mask = mask.is_some_and(|mask| mask.effects.iter().any(|masked| masked.id == effect)); + if on_mask && !def.mask { + return Err(bad(CMD, format!("{} goes on layer content, not on masks", def.label))); + } + Ok((crate::filter_lib::build(def.id, p)?, def.label)) +} + /// The stack (a mask's or a layer's content effects) holding effect `eid`, and its position there. fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec, usize)> { project.layers.values_mut().find_map(|l| { diff --git a/crates/engine/tests/filter_swap.rs b/crates/engine/tests/filter_swap.rs new file mode 100644 index 00000000..87341c60 --- /dev/null +++ b/crates/engine/tests/filter_swap.rs @@ -0,0 +1,94 @@ +//! Swapping a filter effect's type in place through `effect.set {filter}` + +use serde_json::{Value, json}; +use texturecraft_engine::core::{BlendMode, Effect, EffectKind, Filter, LayerId}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, StackTarget, execute}; + +/// A sphere project with its default layer selected +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 256).unwrap() +} + +/// Runs effect-adding `command` and returns the new effect, which it selects +fn add(s: &mut Session, command: &str, params: Value) -> LayerId { + execute(s, command, ¶ms).unwrap(); + let StackTarget::Effect(added) = s.target else { panic!("adding an effect selects it: {:?}", s.target) }; + + added +} + +/// A copy of effect `id` +fn effect(s: &Session, id: LayerId) -> Effect { + s.doc.project.effect(id).unwrap().1.clone() +} + +/// Ids of the selected layer's content effects, bottom first +fn content_order(s: &Session) -> Vec { + let layer = s.selected_layer().unwrap(); + s.doc.project.layer(layer).unwrap().content_effects.iter().map(|effect| effect.id).collect() +} + +#[test] +fn swapping_a_filter_keeps_its_place_blend_opacity_and_visibility() { + let mut s = session(); + let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + let above = add(&mut s, "effect.add.filter", json!({"filter": "grayscale", "target": "content"})); + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4, "visible": false})).unwrap(); + + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur", "radius": 5.0})).unwrap(); + + let blur = effect(&s, swapped); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 5.0), "{:?}", blur.kind); + assert_eq!(blur.name, "Blur", "a default name follows the new filter"); + assert_eq!((blur.blend, blur.opacity, blur.visible), (BlendMode::Multiply, 0.4, false)); + assert_eq!(content_order(&s), vec![below, swapped, above]); +} + +#[test] +fn swapping_a_filter_keeps_a_name_the_user_chose() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content", "name": "Flip"})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold"})).unwrap(); + + assert_eq!(effect(&s, id).name, "Flip"); +} + +#[test] +fn one_undo_restores_the_old_filter() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "threshold", "target": "content", "level": 0.3})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "sharpen"})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + + let restored = effect(&s, id); + assert!(matches!(restored.kind, EffectKind::Filter(Filter::Threshold { level }) if level == 0.3), "{:?}", restored.kind); + assert_eq!(restored.name, "Threshold"); +} + +#[test] +fn a_mask_refuses_a_content_only_filter() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + + let err = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "grayscale"})).unwrap_err(); + + assert!(err.to_string().contains("not on masks"), "{err}"); + assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert))); + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).expect("a mask takes a filter that works on masks"); +} + +#[test] +fn only_filter_effects_swap_and_only_to_filters() { + let mut s = session(); + let levels = add(&mut s, "effect.add.levels", json!({"target": "content"})); + let filter = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + + assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "blur"})).is_err(), "levels is not a filter effect"); + assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "matFinishGrind"})).is_err(), "a material finish is a fill"); + assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "nope"})).is_err()); + assert!(matches!(effect(&s, filter).kind, EffectKind::Filter(Filter::Invert))); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 976a3035..13604e91 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -8,7 +8,7 @@ use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Projection, Source, }; -use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; +use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::{BrushAlpha, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; @@ -19,6 +19,13 @@ use crate::state::PropsTab; use crate::theme::{Tokens, caption}; use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit}; +/// The filter Add filter adds: at its defaults it changes nothing until the slot swaps it +const NEW_FILTER: &str = "hsl"; +const FILTER_SWATCH_WIDTH: f32 = 36.0; +const FILTER_HINT_SIZE: f32 = 10.5; +/// The most colors `effect.set {colors}` takes for a gradient map +const MAX_GRADIENT_STOPS: usize = 16; + const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), Color32::from_rgb(0xd0, 0x80, 0x30), @@ -208,48 +215,34 @@ pub(crate) fn targets_content(app: &TextureCraftApp) -> bool { } } -/// "Add effect" items for `layer` (toolbar and context menu). Effects that fit both stacks go -/// to the content when it is the selected target; generators and compare always go to the -/// mask, anchor points to the content. +/// "Add effect" items for `layer`: content when it is the selected target, else the mask fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let content = !layer.is_group() && app.session.selected_layer() == Some(layer.id) && targets_content(app); - let t = if content { "content" } else { "mask" }; + let target = if content { "content" } else { "mask" }; ui.label(caption(if content { tr("Add to the layer content") } else { tr("Add to the mask") })); + + // Generators and compare masks always go to the mask, anchor points to the content let items = [ (tr("Add generator"), "effect.add.generator", json!({})), - (tr("Add paint"), "effect.add.paint", json!({"target": t})), - (tr("Add fill"), "effect.add.fill", json!({"target": t})), - (tr("Add levels"), "effect.add.levels", json!({"target": t})), + (tr("Add paint"), "effect.add.paint", json!({"target": target})), + (tr("Add fill"), "effect.add.fill", json!({"target": target})), + (tr("Add levels"), "effect.add.levels", json!({"target": target})), (tr("Add compare mask"), "effect.add.compare", json!({})), + (tr("Add filter"), "effect.add.filter", json!({"target": target, "filter": NEW_FILTER})), (tr("Add anchor point"), "effect.add.anchor", json!({})), ]; - let run = |app: &mut TextureCraftApp, id: &str, p: &Value| { + for (label, command, params) in items { + let enabled = command != "effect.add.anchor" || !layer.is_group(); + if !ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + continue; + } + if app.session.selected_layer() != Some(layer.id) { app.run("layer.select", json!({"layer": layer.id.0})); } - app.run(id, with(p, json!({"layer": layer.id.0}))); - }; - for (label, id, p) in items { - let enabled = id != "effect.add.anchor" || !layer.is_group(); - if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { - run(app, id, &p); - ui.close(); - } + app.run(command, with(¶ms, json!({"layer": layer.id.0}))); + ui.close(); } - // The filter library (material finishes only fill content). - ui.menu_button(tr("Add filter"), |ui| { - let mut group = ""; - for f in FILTERS.iter().filter(|f| content || f.mask) { - if f.group != group { - ui.label(caption(tr(f.group))); - group = f.group; - } - if ui.button(tr(f.label)).clicked() { - run(app, "effect.add.filter", &json!({"target": t, "filter": f.id})); - ui.close(); - } - } - }); } fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) { @@ -2058,82 +2051,85 @@ fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: Laye } } -/// The parameters of filter effect `id`. -fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) { +/// The filter slot and the parameters of filter effect `id` +fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &Filter) { let tk = Tokens::get(ui.ctx()); - let set = |app: &mut TextureCraftApp, key: &str, v: Value, merge: bool| { - let mut p = json!({ "effect": id, "merge": merge }); - p[key] = v; - app.run("effect.set", p); + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + let mut params = json!({ "effect": id, "merge": merge }); + params[key] = value; + app.run("effect.set", params); }; - ui.label(caption(tr(f.label()))); - if let Filter::Hsl { hue, .. } = f { - let mut h = hue * 360.0; - if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut h, -180.0..=180.0, 0) { - set(app, "hue", json!(h / 360.0), merge); + crate::filter_slot::show(app, ui, id, filter); + + if let Filter::Hsl { hue, .. } = filter { + let mut degrees = hue * 360.0; + if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut degrees, -180.0..=180.0, 0) { + set(app, "hue", json!(degrees / 360.0), merge); } } - for (key, label, mut v, lo, hi) in scalar_params(f) { + + for (key, label, mut value, min, max) in scalar_params(filter) { let decimals = if matches!(key, "seed" | "levels") { 0 - } else if hi - lo > 10.0 { + } else if max - min > 10.0 { 1 } else { 2 }; - if let Some(merge) = slider_edit(ui, tr(label), &mut v, lo..=hi, decimals) { - set(app, key, json!(v), merge); + if let Some(merge) = slider_edit(ui, tr(label), &mut value, min..=max, decimals) { + set(app, key, json!(value), merge); } } - match f { + + match filter { Filter::ColorBalance { shadows, midtones, highlights } => { for (key, label, rgb) in [("shadows", tr("Shadows"), shadows), ("midtones", tr("Midtones"), midtones), ("highlights", tr("Highlights"), highlights)] { ui.label(RichText::new(label).strong()); - let mut v = *rgb; + let mut balance = *rgb; let mut edit = None; - for (x, name) in v.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) { - edit = edit.or(slider_edit(ui, name, x, -1.0..=1.0, 2)); + for (component, name) in balance.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) { + edit = edit.or(slider_edit(ui, name, component, -1.0..=1.0, 2)); } if let Some(merge) = edit { - set(app, key, json!(v), merge); + set(app, key, json!(balance), merge); } } } Filter::ReplaceColor { from, to, .. } => { for (key, label, rgb) in [("from", tr("Color to replace"), from), ("to", tr("Replacement color"), to)] { - let mut v = *rgb; + let mut color = *rgb; ui.horizontal(|ui| { - if color_swatch(ui, &format!("replace_{key}_{id}"), &mut v, 36.0) { - set(app, key, json!(v), false); + if color_swatch(ui, &format!("replace_{key}_{id}"), &mut color, FILTER_SWATCH_WIDTH) { + set(app, key, json!(color), false); } ui.label(label); }); } - ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } Filter::GradientMap { colors } => { - let mut c = colors.clone(); + let mut stops = colors.clone(); let mut changed = false; ui.horizontal_wrapped(|ui| { - for (i, col) in c.iter_mut().enumerate() { - changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), col, 36.0); + for (i, stop) in stops.iter_mut().enumerate() { + changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), stop, FILTER_SWATCH_WIDTH); } }); ui.horizontal(|ui| { - if ui.add_enabled(c.len() < 16, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() { - c.push(c.last().copied().unwrap_or([1.0; 3])); + if ui.add_enabled(stops.len() < MAX_GRADIENT_STOPS, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() { + stops.push(stops.last().copied().unwrap_or([1.0; 3])); changed = true; } - if ui.add_enabled(c.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { - c.pop(); + if ui.add_enabled(stops.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { + stops.pop(); changed = true; } }); if changed { - set(app, "colors", json!(c), false); + set(app, "colors", json!(stops), false); } - ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } Filter::Warp { .. } | Filter::DirectionalBlur { .. } @@ -2144,7 +2140,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter | Filter::Bevel { .. } | Filter::Mosaic { .. } | Filter::Glow { .. } => { - ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } _ => {} } diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs new file mode 100644 index 00000000..7a143612 --- /dev/null +++ b/crates/ui-egui/src/filter_slot.rs @@ -0,0 +1,83 @@ +//! The filter slot atop a filter's properties: thumbnail and name, opening a picker that swaps it + +use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{Filter, LayerId}; +use texturecraft_engine::filter_lib::{FILTERS, find}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::shelf_preview::ShelfPreview; +use crate::theme::Tokens; +use crate::thumbs::Thumbs; + +const SLOT_HEIGHT: f32 = 52.0; +const SLOT_ROUNDING: f32 = 3.0; +const THUMBNAIL_SIZE: f32 = 40.0; +const THUMBNAIL_INSET: f32 = 6.0; +const CAPTION_FONT_SIZE: f32 = 11.0; +const NAME_FONT_SIZE: f32 = 13.0; +/// Gap between the caption's and the name's centers +const LINE_GAP: f32 = 15.0; +const CARET_INSET: f32 = 14.0; +const CARET_FONT_SIZE: f32 = 14.0; + +/// The slot of filter effect `effect`: a pick runs `effect.set {filter}`, masks offer only mask filters +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: &Filter) { + let ctx = ui.ctx().clone(); + let on_mask = is_on_mask(app, effect); + let current = find(filter.label()).map(|def| def.id); + let thumbnail = current.and_then(|id| app.thumbs.filter(&ctx, id)); + let name = tr(filter.label()); + + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name)); + paint(ui, rect, response.hovered(), thumbnail.as_ref(), name); + + let popup = ui.make_persistent_id(("filter_picker", effect)); + if response.clicked() { + resource_picker::toggle(&ctx, popup); + } + + let items = |thumbs: &mut Thumbs| { + FILTERS + .iter() + .filter(|def| def.is_filter_effect() && (def.mask || !on_mask)) + .map(|def| ResourcePickerItem { id: def.id, label: tr(def.label), group: tr(def.group), thumbnail: thumbs.filter(&ctx, def.id) }) + .collect() + }; + let picked = resource_picker::show(&response, popup, &mut app.thumbs, current, items, ShelfPreview::Filter); + if let Some(id) = picked.filter(|id| Some(*id) != current) { + app.run("effect.set", json!({"effect": effect, "filter": id})); + } +} + +/// Whether filter effect `effect` sits in a mask rather than the layer content +fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { + let project = &app.session.doc.project; + let owner = project.effect(LayerId(effect)).and_then(|(owner, _)| project.layers.get(&owner)); + owner.and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|masked| masked.id.0 == effect)) +} + +/// The slot's box: thumbnail, "Filter" over the name, caret +fn paint(ui: &Ui, rect: Rect, hovered: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) { + let tk = Tokens::get(ui.ctx()); + let painter = ui.painter(); + let (fill, border) = if hovered { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; + painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(1.0, border), egui::StrokeKind::Inside); + + if let Some(texture) = thumbnail { + let image = Rect::from_min_size(pos2(rect.left() + THUMBNAIL_INSET, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + painter.image(texture.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + + let center = rect.center(); + painter.text(center - vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, tr("Filter"), FontId::proportional(CAPTION_FONT_SIZE), tk.text_dim); + painter.text(center + vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, name, FontId::proportional(NAME_FONT_SIZE), tk.text_strong); + + let caret_color = if hovered { tk.text } else { tk.text_dim }; + painter.text(pos2(rect.right() - CARET_INSET, center.y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..c61f4ce3 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -304,6 +304,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "تعبئة"), ("Fill the closed path (lasso)", "تعبئة المسار المغلق (حبل التحديد)"), ("Fill the path (close it first)", "تعبئة المسار (أغلقه أولاً)"), + ("Filter", "مرشح"), ("Filter the remaining noise while keeping edges and texture detail", "تصفية الضوضاء المتبقية مع الحفاظ على الحواف وتفاصيل الخامة"), ("Filters", "مرشحات"), ("Fine noise", "ضوضاء دقيقة"), @@ -677,6 +678,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "خدوش"), ("Screen", "شاشة (Screen)"), ("Screenshot of the viewport", "لقطة شاشة لمنفذ العرض"), + ("Search", "بحث"), ("Search all assets", "البحث في جميع الأصول"), ("Search commands or keys", "البحث في الأوامر أو المفاتيح"), ("Seed", "البذرة العشوائية (Seed)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..18a2c94b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -328,6 +328,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Füllung"), ("Fill the closed path (lasso)", "Geschlossenen Pfad füllen (Lasso)"), ("Fill the path (close it first)", "Pfad füllen (zuerst schließen)"), + ("Filter", "Filter"), ("Filter the remaining noise while keeping edges and texture detail", "Restrauschen filtern und dabei Kanten und Texturdetails erhalten"), ("Filters", "Filter"), ("Fine noise", "Feines Rauschen"), @@ -716,6 +717,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Kratzer"), ("Screen", "Negativ multiplizieren"), ("Screenshot of the viewport", "Screenshot des Ansichtsfensters"), + ("Search", "Suchen"), ("Search all assets", "Alle Assets durchsuchen"), ("Search commands or keys", "Befehle oder Tasten suchen"), ("Seed", "Startwert"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..e0c7842b 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -319,6 +319,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Relleno"), ("Fill the closed path (lasso)", "Rellenar el trazado cerrado (lazo)"), ("Fill the path (close it first)", "Rellenar el trazado (ciérralo antes)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrar el ruido restante conservando los bordes y el detalle de la textura"), ("Filters", "Filtros"), ("Fine noise", "Ruido fino"), @@ -704,6 +705,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Arañazos"), ("Screen", "Trama"), ("Screenshot of the viewport", "Captura de la ventana gráfica"), + ("Search", "Buscar"), ("Search all assets", "Buscar en todos los recursos"), ("Search commands or keys", "Buscar comandos o teclas"), ("Seed", "Semilla"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..20209ab5 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -331,6 +331,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Remplissage"), ("Fill the closed path (lasso)", "Remplir le tracé fermé (lasso)"), ("Fill the path (close it first)", "Remplir le tracé (le fermer d'abord)"), + ("Filter", "Filtre"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrer le bruit restant en préservant les contours et les détails de texture"), ("Filters", "Filtres"), ("Fine noise", "Bruit fin"), @@ -722,6 +723,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Rayures"), ("Screen", "Superposition"), ("Screenshot of the viewport", "Capture de la fenêtre d'affichage"), + ("Search", "Rechercher"), ("Search all assets", "Rechercher dans toutes les ressources"), ("Search commands or keys", "Rechercher des commandes ou des touches"), ("Seed", "Graine"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..8388adcc 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -325,6 +325,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Riempimento"), ("Fill the closed path (lasso)", "Riempi il tracciato chiuso (lazo)"), ("Fill the path (close it first)", "Riempi il tracciato (prima chiudilo)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtra il rumore residuo preservando i bordi e i dettagli della texture"), ("Filters", "Filtri"), ("Fine noise", "Rumore fine"), @@ -713,6 +714,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Graffi"), ("Screen", "Scolora"), ("Screenshot of the viewport", "Screenshot della viewport"), + ("Search", "Cerca"), ("Search all assets", "Cerca in tutte le risorse"), ("Search commands or keys", "Cerca comandi o tasti"), ("Seed", "Seme"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..b20c9d55 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -316,6 +316,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "塗りつぶし"), ("Fill the closed path (lasso)", "閉じたパスを塗りつぶし (なげなわ)"), ("Fill the path (close it first)", "パスを塗りつぶし (先にパスを閉じる)"), + ("Filter", "フィルター"), ("Filter the remaining noise while keeping edges and texture detail", "エッジとテクスチャのディテールを保ちながら残りのノイズを除去"), ("Filters", "フィルター"), ("Fine noise", "細かいノイズ"), @@ -695,6 +696,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "引っかき傷"), ("Screen", "スクリーン"), ("Screenshot of the viewport", "ビューポートのスクリーンショット"), + ("Search", "検索"), ("Search all assets", "すべてのアセットを検索"), ("Search commands or keys", "コマンドまたはキーを検索"), ("Seed", "シード"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..9837b49f 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -313,6 +313,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "채우기"), ("Fill the closed path (lasso)", "닫힌 패스를 채웁니다 (올가미)"), ("Fill the path (close it first)", "패스를 채웁니다 (먼저 패스를 닫으세요)"), + ("Filter", "필터"), ("Filter the remaining noise while keeping edges and texture detail", "가장자리와 텍스처 디테일을 유지하면서 남은 노이즈를 걸러냅니다"), ("Filters", "필터"), ("Fine noise", "미세 노이즈"), @@ -686,6 +687,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "스크래치"), ("Screen", "스크린"), ("Screenshot of the viewport", "뷰포트 스크린샷"), + ("Search", "검색"), ("Search all assets", "모든 에셋 검색"), ("Search commands or keys", "명령 또는 키 검색"), ("Seed", "시드"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..7badff49 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -319,6 +319,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Preenchimento"), ("Fill the closed path (lasso)", "Preencher o caminho fechado (laço)"), ("Fill the path (close it first)", "Preencher o caminho (feche-o primeiro)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrar o ruído restante preservando bordas e detalhes de textura"), ("Filters", "Filtros"), ("Fine noise", "Ruído fino"), @@ -701,6 +702,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Arranhões"), ("Screen", "Tela"), ("Screenshot of the viewport", "Captura de tela da viewport"), + ("Search", "Pesquisar"), ("Search all assets", "Pesquisar em todos os recursos"), ("Search commands or keys", "Pesquisar comandos ou teclas"), ("Seed", "Semente"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..4afec91d 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -286,6 +286,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "填充"), ("Fill the closed path (lasso)", "填充闭合路径(套索)"), ("Fill the path (close it first)", "填充路径(请先闭合)"), + ("Filter", "滤镜"), ("Filter the remaining noise while keeping edges and texture detail", "在保留边缘和纹理细节的同时过滤剩余噪点"), ("Filters", "滤镜"), ("Fine noise", "细噪波"), @@ -647,6 +648,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "划痕"), ("Screen", "滤色"), ("Screenshot of the viewport", "视口截图"), + ("Search", "搜索"), ("Search all assets", "搜索所有资产"), ("Search commands or keys", "搜索命令或按键"), ("Seed", "随机种子"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..4db0acd7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -12,6 +12,7 @@ pub mod control; pub mod dock; pub mod docking; pub mod export_templates; +mod filter_slot; pub mod fonts; pub mod gpu; pub mod i18n; @@ -26,6 +27,8 @@ mod preview_worker; pub mod profile; pub mod properties_popup; pub mod render_mode; +mod resource_picker; +mod resource_picker_item; pub mod shelf; pub mod shelf_preview; pub mod state; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index b74aa300..3f645eeb 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -305,6 +305,7 @@ fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { } } +/// Runs the commands bound to the keys pressed this frame, outside text fields and key capture pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if crate::keymap::capturing(ctx) || (ctx.memory(|memory| memory.focused().is_some()) && ctx.egui_wants_keyboard_input()) { return; @@ -319,6 +320,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } + // Escape closes an open popup first, before the Properties popup or the stroke + let popup_open = egui::Popup::is_any_open(ctx); + let active_shortcuts = crate::keymap::active(&app.ui.keymap); let mut commands_to_invoke: Vec<&str> = Vec::new(); ctx.input_mut(|input| { @@ -337,9 +341,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - if app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; - } else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.tool.path.points.clear(); app.session.tool.path.editing = None; diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs new file mode 100644 index 00000000..5b119c2f --- /dev/null +++ b/crates/ui-egui/src/resource_picker.rs @@ -0,0 +1,126 @@ +//! A popup under a slot that picks a resource, such as a filter, from grouped shelf tiles searched by name + +use egui::{Id, Response, Stroke, Ui}; + +use crate::i18n::tr; +use crate::resource_picker_item::ResourcePickerItem; +use crate::shelf; +use crate::shelf_preview::ShelfPreview; +use crate::theme::Tokens; +use crate::thumbs::Thumbs; + +/// Four shelf tiles and the scrollbar +const PICKER_WIDTH: f32 = 320.0; +/// The grid's height, fixed so the popup keeps its place while searching +const PICKER_HEIGHT: f32 = 340.0; +const CURRENT_OUTLINE_WIDTH: f32 = 1.5; +const TILE_ROUNDING: f32 = 3.0; + +/// Opens the picker `popup_id` with an empty, focused search field, or closes it +pub(crate) fn toggle(ctx: &egui::Context, popup_id: Id) { + if egui::Popup::is_id_open(ctx, popup_id) { + egui::Popup::close_id(ctx, popup_id); + return; + } + + egui::Popup::open_id(ctx, popup_id); + ctx.data_mut(|data| { + data.insert_temp(search_id(popup_id), String::new()); + data.insert_temp(focus_id(popup_id), true); + }); +} + +/// Draws picker `popup_id` at `slot` while open and returns the id clicked (`items` runs only then) +pub(crate) fn show( + slot: &Response, + popup_id: Id, + thumbs: &mut Thumbs, + current: Option<&str>, + items: impl FnOnce(&mut Thumbs) -> Vec, + preview: impl Fn(&'static str) -> ShelfPreview, +) -> Option<&'static str> { + let ctx = slot.ctx.clone(); + if !egui::Popup::is_id_open(&ctx, popup_id) { + return None; + } + + let items = items(thumbs); + let mut picked = None; + egui::Popup::from_response(slot) + .id(popup_id) + .open_memory(None) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .align(egui::RectAlign::BOTTOM_END) + .width(PICKER_WIDTH) + .show(|ui| { + ui.set_width(PICKER_WIDTH); + let just_opened = ui.data_mut(|data| data.remove_temp::(focus_id(popup_id))).unwrap_or(false); + let query = search_field(ui, popup_id, just_opened); + egui::ScrollArea::vertical().max_height(PICKER_HEIGHT).show(ui, |ui| { + // A search that leaves few tiles must not shrink the popup, or egui moves it + ui.set_min_height(PICKER_HEIGHT); + picked = grid(ui, thumbs, &items, &query, current, just_opened, &preview); + }); + }); + + if picked.is_some() { + egui::Popup::close_id(&ctx, popup_id); + } + picked +} + +/// The search field, focused the frame the picker opens; returns the lowercase query +fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String { + let mut search: String = ui.data(|data| data.get_temp(search_id(popup_id))).unwrap_or_default(); + let field = ui.add(egui::TextEdit::singleline(&mut search).hint_text(tr("Search")).desired_width(f32::INFINITY)); + if just_opened { + field.request_focus(); + } + + let query = search.trim().to_lowercase(); + ui.data_mut(|data| data.insert_temp(search_id(popup_id), search)); + query +} + +/// The items matching `query` as tiles under group headers, `current` outlined; returns the one clicked +fn grid( + ui: &mut Ui, + thumbs: &mut Thumbs, + items: &[ResourcePickerItem], + query: &str, + current: Option<&str>, + reveal_current: bool, + preview: &impl Fn(&'static str) -> ShelfPreview, +) -> Option<&'static str> { + let tk = Tokens::get(ui.ctx()); + let shown: Vec<&ResourcePickerItem> = items.iter().filter(|item| shelf::matches(query, &[item.label, item.id])).collect(); + let mut picked = None; + for group in shelf::categories(&shown, |item| item.group) { + shelf::header(ui, group); + shelf::tiles(ui, |ui| { + for item in shown.iter().filter(|item| item.group == group) { + let response = shelf::tile(ui, thumbs, item.thumbnail.as_ref(), || preview(item.id), item.label, None); + if current == Some(item.id) { + if reveal_current { + response.scroll_to_me(Some(egui::Align::Center)); + } + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tk.accent), egui::StrokeKind::Inside); + } + if response.clicked() { + picked = Some(item.id); + } + } + }); + } + picked +} + +/// Where the picker keeps its search text +fn search_id(popup_id: Id) -> Id { + popup_id.with("search") +} + +/// Set while the picker waits for its first frame open +fn focus_id(popup_id: Id) -> Id { + popup_id.with("focus") +} diff --git a/crates/ui-egui/src/resource_picker_item.rs b/crates/ui-egui/src/resource_picker_item.rs new file mode 100644 index 00000000..5b9e8071 --- /dev/null +++ b/crates/ui-egui/src/resource_picker_item.rs @@ -0,0 +1,9 @@ +//! One choice offered by a resource picker + +/// A resource the picker offers: its id, translated label and group, and its thumbnail +pub(crate) struct ResourcePickerItem { + pub id: &'static str, + pub label: &'static str, + pub group: &'static str, + pub thumbnail: Option, +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 46ced908..55ef400f 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -266,7 +266,7 @@ fn drag_preview(ctx: &egui::Context) { p.galley(rect.min + vec2(6.0, 3.0), galley, tk.text_strong); } -fn matches(filter: &str, texts: &[&str]) -> bool { +pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool { filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter)) } @@ -275,13 +275,13 @@ fn title(ui: &mut Ui, text: &str) { ui.label(RichText::new(text).strong().color(tk.text_strong)); } -fn header(ui: &mut Ui, text: &str) { +pub(crate) fn header(ui: &mut Ui, text: &str) { let tk = Tokens::get(ui.ctx()); ui.add_space(2.0); ui.label(RichText::new(text).size(11.0).color(tk.text_dim)); } -fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { +pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = vec2(4.0, 4.0); body(ui); @@ -290,7 +290,7 @@ fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { } /// The distinct categories of `items`, in order of first appearance. -fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'static str> { +pub(crate) fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'static str> { let mut out: Vec<&'static str> = Vec::new(); for c in items.iter().map(category) { if !out.contains(&c) { @@ -586,7 +586,7 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: } /// Asset tile with optional dragging and a larger hover preview -fn tile( +pub(crate) fn tile( ui: &mut Ui, thumbs: &mut Thumbs, tex: Option<&egui::TextureHandle>, diff --git a/crates/ui-egui/tests/filter_picker.rs b/crates/ui-egui/tests/filter_picker.rs new file mode 100644 index 00000000..31daef69 --- /dev/null +++ b/crates/ui-egui/tests/filter_picker.rs @@ -0,0 +1,81 @@ +//! The filter slot in Properties swaps a filter through its picker, and Add filter adds one + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Filter, LayerId}; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The app with an Invert filter on a fill layer's content, selected so Properties shows its slot +fn app_with_invert() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + let effect = execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); + let effect = LayerId(effect["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap(); + session.target = StackTarget::Effect(effect); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + (harness, effect) +} + +/// The kind of effect `effect` now +fn kind(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> EffectKind { + harness.state().session.doc.project.effect(effect).unwrap().1.kind.clone() +} + +/// Clicks the Invert slot, which opens its picker +fn open_picker(harness: &mut Harness<'_, TextureCraftApp>) { + harness.get_by_role_and_label(Role::ComboBox, "Invert").click(); + harness.run_steps(3); + assert!(egui::Popup::is_any_open(&harness.ctx), "clicking the slot opens the picker"); +} + +#[test] +fn picking_from_the_slot_swaps_the_filter() { + let (mut harness, effect) = app_with_invert(); + open_picker(&mut harness); + + // The picker's search field has the focus as it opens + harness.event(egui::Event::Text("sharp".into())); + harness.run_steps(3); + assert_eq!(harness.query_all_by_label("Blur").count(), 0, "the search hides filters that don't match"); + + harness.get_by_label("Sharpen").click(); + harness.run_steps(3); + + assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, effect)); + assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); +} + +#[test] +fn escape_closes_the_picker_without_changes() { + let (mut harness, effect) = app_with_invert(); + open_picker(&mut harness); + + // Without the search field's focus, the painting shortcuts see Escape first + harness.ctx.memory_mut(|memory| memory.stop_text_input()); + harness.run_steps(2); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + assert!(!egui::Popup::is_any_open(&harness.ctx)); + assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); +} + +#[test] +fn add_filter_adds_a_filter_and_selects_it() { + let (mut harness, _) = app_with_invert(); + harness.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); + harness.run_steps(3); + + harness.get_by_label("Add filter").click(); + harness.run_steps(3); + + let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Properties shows the new filter's slot"); +} From a1d010ccb2f131c867f4551f1d12f1fa47911052 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 08:20:33 +0000 Subject: [PATCH 41/73] Curvature generators: mode and detail sizes Curvature and edge wear generators read the baked curvature map one texel at a time, so they only marked the sharpest edges. They now take a mode (edges, cavities, both, raw) and seven detail size weights: the map itself and the map blurred at 1 to 32 texels at 2K, padded past the UV islands and built once per map and layout. Each size's edges and cavities combine like a screen blend. New curvature and edge wear generators use detail sizes. Generators saved without them, and smart masks, read the map exactly as before. --- crates/compose/src/curvature_size_level.rs | 42 ++++ crates/compose/src/curvature_sizes.rs | 133 +++++++++++++ crates/compose/src/eval.rs | 215 +++++++++++++++------ crates/compose/src/lib.rs | 2 + crates/core/src/layer.rs | 31 ++- crates/core/src/layer/curvature_detail.rs | 22 +++ crates/core/src/layer/curvature_mode.rs | 34 ++++ crates/core/src/lib.rs | 5 +- crates/engine/src/inspect.rs | 59 +++--- crates/engine/src/mask_cmds.rs | 140 ++++++++------ crates/engine/src/smart_masks.rs | 6 +- crates/engine/tests/session.rs | 20 ++ crates/ui-egui/src/dock.rs | 185 +++++++++++------- crates/ui-egui/src/i18n/ar.rs | 9 + crates/ui-egui/src/i18n/de.rs | 9 + crates/ui-egui/src/i18n/es.rs | 9 + crates/ui-egui/src/i18n/fr.rs | 9 + crates/ui-egui/src/i18n/it.rs | 9 + crates/ui-egui/src/i18n/ja.rs | 9 + crates/ui-egui/src/i18n/ko.rs | 9 + crates/ui-egui/src/i18n/pt_br.rs | 9 + crates/ui-egui/src/i18n/zh_hans.rs | 6 + 22 files changed, 753 insertions(+), 219 deletions(-) create mode 100644 crates/compose/src/curvature_size_level.rs create mode 100644 crates/compose/src/curvature_sizes.rs create mode 100644 crates/core/src/layer/curvature_detail.rs create mode 100644 crates/core/src/layer/curvature_mode.rs diff --git a/crates/compose/src/curvature_size_level.rs b/crates/compose/src/curvature_size_level.rs new file mode 100644 index 00000000..aa09d747 --- /dev/null +++ b/crates/compose/src/curvature_size_level.rs @@ -0,0 +1,42 @@ +/// Deviations of ±0.5 (curvature − 0.5) stored as 16-bit integers. +pub const DEVIATION_SCALE: f32 = i16::MAX as f32 * 2.0; + +/// Curvature blurred at one detail size: deviations from flat, stored `step` times coarser than the map. +pub struct CurvatureSizeLevel { + pub step: u32, + pub width: u32, + pub height: u32, + pub deviation: Vec, +} + +impl CurvatureSizeLevel { + /// The deviation at map texel `(x, y)`, bilinear between the stored texels. + pub fn sample(&self, x: u32, y: u32) -> f32 { + if self.width == 0 || self.height == 0 { + return 0.0; + } + + let to_level = |texel: u32| (texel as f32 + 0.5) / self.step as f32 - 0.5; + let (level_x, level_y) = (to_level(x).max(0.0), to_level(y).max(0.0)); + let (x0, y0) = ((level_x.floor() as u32).min(self.width - 1), (level_y.floor() as u32).min(self.height - 1)); + let (x1, y1) = ((x0 + 1).min(self.width - 1), (y0 + 1).min(self.height - 1)); + let (blend_x, blend_y) = (level_x - x0 as f32, level_y - y0 as f32); + let stored = |x: u32, y: u32| self.deviation.get((y * self.width + x) as usize).map_or(0.0, |value| f32::from(*value) / DEVIATION_SCALE); + let top = stored(x0, y0) + (stored(x1, y0) - stored(x0, y0)) * blend_x; + let bottom = stored(x0, y1) + (stored(x1, y1) - stored(x0, y1)) * blend_x; + top + (bottom - top) * blend_y + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn samples_blend_the_stored_texels() { + let level = CurvatureSizeLevel { step: 2, width: 2, height: 1, deviation: vec![0, (0.25 * DEVIATION_SCALE) as i16] }; + assert!(level.sample(0, 0).abs() < 1e-4, "the first stored texel covers map texels 0 and 1"); + assert!((level.sample(3, 0) - 0.25).abs() < 1e-3); + assert!(level.sample(2, 0) > 0.0 && level.sample(2, 0) < 0.25, "between stored texels the value blends"); + } +} diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs new file mode 100644 index 00000000..c2dfe755 --- /dev/null +++ b/crates/compose/src/curvature_sizes.rs @@ -0,0 +1,133 @@ +//! The baked curvature map at the detail sizes of curvature generators, built once per map and layout. + +use std::sync::{Arc, Mutex, Weak}; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail}; +use texturecraft_texel::dilate::{DilationMap, NONE}; + +use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE}; +use crate::eval::{Inputs, blur}; + +/// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. +pub struct CurvatureSizes { + pub levels: Vec, +} + +/// Built sizes by the curvature data they come from, the working texture size, the UV tile block and the tiles' scales. +type CacheEntry = (Weak>, (u32, u32), (u32, u32), BlockScales, Arc); + +static CACHE: Mutex> = Mutex::new(Vec::new()); + +impl CurvatureSizes { + /// The sizes of the texture set `inp` composites (None without a baked curvature map). + pub fn of(inp: &Inputs) -> Option> { + let curvature = inp.baked.maps.get(&BakedMap::Curvature)?; + let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); + let block = grid.map_or((width, height), |grid| (width / grid.cols.max(1), height / grid.rows.max(1))); + let working_size = (inp.gbuf.width, inp.gbuf.height); + + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.retain(|(source, ..)| source.strong_count() > 0); + let same_source = |source: &Weak>| source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)); + let cached = cache.iter().find(|(source, cached_size, cached_block, cached_scales, _)| { + same_source(source) && *cached_size == working_size && *cached_block == block && *cached_scales == inp.block_scales + }); + if let Some((.., sizes)) = cached { + return Some(sizes.clone()); + } + + // Covered working texels mark where they land in the bake atlas + let mut covered = vec![false; (width * height) as usize]; + for texel in (0..working_size.0 * working_size.1).filter(|texel| inp.gbuf.covered(*texel as usize)) { + let uv = [((texel % working_size.0) as f32 + 0.5) / working_size.0 as f32, ((texel / working_size.0) as f32 + 0.5) / working_size.1 as f32]; + if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) { + let (baked_x, baked_y) = ((baked_uv[0] * width as f32) as u32, (baked_uv[1] * height as f32) as u32); + if let Some(slot) = covered.get_mut((baked_y.min(height - 1) * width + baked_x.min(width - 1)) as usize) { + *slot = true; + } + } + } + + let sizes = Arc::new(CurvatureSizes::build(curvature, (width, height), &covered, block)); + cache.push((Arc::downgrade(curvature), working_size, block, inp.block_scales.clone(), sizes.clone())); + Some(sizes) + } + + /// Pad `curvature` from its `covered` texels within each UV tile `block`, then blur each block at every size. + fn build(curvature: &[f32], (width, height): (u32, u32), covered: &[bool], block: (u32, u32)) -> CurvatureSizes { + let padding = DilationMap::in_rectangular_blocks(covered, width, height, None, block); + let deviation: Vec = + padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect(); + let (block_width, block_height) = (block.0.max(1).min(width), block.1.max(1).min(height)); + + let levels = CurvatureDetail::SIZES + .iter() + .skip(1) + .map(|size| { + // Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser + let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32; + let step = (radius / 2).max(1).next_power_of_two(); + + let mut blurred = deviation.clone(); + for block_y in (0..height).step_by(block_height as usize) { + for block_x in (0..width).step_by(block_width as usize) { + let region = (block_x, block_y, block_width.min(width - block_x), block_height.min(height - block_y)); + blur_block(&mut blurred, width, region, radius); + } + } + coarsen(&blurred, (width, height), step) + }) + .collect(); + CurvatureSizes { levels } + } +} + +/// Blur the `(x0, y0, w, h)` block of `data` (`width` texels per row) in place, reading nothing outside it. +fn blur_block(data: &mut [f32], width: u32, (x0, y0, w, h): (u32, u32, u32, u32), radius: u32) { + let mut block: Vec = + (y0..y0 + h).flat_map(|y| (x0..x0 + w).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect(); + blur(&mut block, w as usize, h as usize, radius as usize); + + for (row, values) in block.chunks(w as usize).enumerate() { + let start = ((y0 + row as u32) * width + x0) as usize; + if let Some(target) = data.get_mut(start..start + values.len()) { + target.copy_from_slice(values); + } + } +} + +/// `data` averaged over `step × step` squares (the last ones clipped to the map). +fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32) -> CurvatureSizeLevel { + let (coarse_width, coarse_height) = (width.div_ceil(step), height.div_ceil(step)); + let deviation = (0..coarse_width * coarse_height) + .into_par_iter() + .map(|cell| { + let (cell_x, cell_y) = (cell % coarse_width, cell / coarse_width); + let columns = cell_x * step..((cell_x + 1) * step).min(width); + let rows = cell_y * step..((cell_y + 1) * step).min(height); + let count = (columns.len() * rows.len()).max(1) as f32; + let texels = rows.flat_map(|y| columns.clone().map(move |x| (y * width + x) as usize)); + let mean = texels.map(|index| data.get(index).copied().unwrap_or(0.0)).sum::() / count; + (mean * DEVIATION_SCALE).round().clamp(i16::MIN as f32, i16::MAX as f32) as i16 + }) + .collect(); + CurvatureSizeLevel { step, width: coarse_width, height: coarse_height, deviation } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn padding_keeps_an_island_border_from_reading_flat() { + let left_half = |texel: u32| texel % 64 < 32; + let curvature: Vec = (0..64 * 64).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect(); + let covered: Vec = (0..64 * 64).map(left_half).collect(); + let sizes = CurvatureSizes::build(&curvature, (64, 64), &covered, (64, 64)); + for level in &sizes.levels { + assert!((level.sample(31, 32) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it"); + } + } +} diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index c2287a4b..412cfe58 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -4,17 +4,20 @@ use std::borrow::Cow; use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, - LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, + BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Generator, + GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, + blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; use crate::below::{Band, BelowCache, Level}; +use crate::curvature_sizes::CurvatureSizes; use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise}; use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; @@ -204,6 +207,8 @@ struct EffectPlan<'a> { opacity: f32, data: Option>, preview: bool, + /// The curvature detail sizes a generator with detail reads. + curvature_sizes: Option>, } struct MaskPlan<'a> { @@ -304,6 +309,12 @@ fn direction(angle: f32) -> [f32; 2] { [cs, -sn] } +/// Gain on the curvature map's own deviation from flat (±0.5 reaches black and white). +const MAP_GAIN: f32 = 2.0; + +/// Gain per texel of a detail size: blurring spreads an edge over about twice its radius, so wider sizes need proportionally more to reach full strength. +const GAIN_PER_DETAIL_TEXEL: f32 = 2.0 * std::f32::consts::SQRT_2; + /// Samples along a directional or slope blur at most (beyond, samples spread out). const LINE_SAMPLES: i32 = 24; @@ -423,7 +434,7 @@ const FIX: f64 = (1u64 << 24) as f64; /// Three running-sum box blurs (≈ Gaussian) of a `w × h` image along rows then along columns. /// Rows (and columns, transposed) blur in parallel. -fn blur(data: &mut [f32], w: usize, h: usize, r: usize) { +pub(crate) fn blur(data: &mut [f32], w: usize, h: usize, r: usize) { let fix = |v: &f32| if v.is_finite() { (f64::from(v.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; let mut v: Vec = data.par_iter().map(fix).collect(); blur_rows(&mut v, w, r); @@ -808,12 +819,14 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, c Some(c) => (inp.pixels.layer(e.id, c), PaintTarget::Layer(e.id)), None => (inp.pixels.masks.get(&e.id), PaintTarget::Mask(e.id)), }; + let reads_detail = matches!(&e.kind, EffectKind::Generator(generator) if generator.detail.is_some()); EffectPlan { kind: &e.kind, blend: e.blend, opacity: e.opacity, data: if e.kind.painted() { tile_of(inp, img, tx, ty, channel) } else { None }, preview: previews(inp, target), + curvature_sizes: if reads_detail { CurvatureSizes::of(inp) } else { None }, } }) .collect() @@ -1166,94 +1179,130 @@ impl<'a, 'b> Texel<'a, 'b> { } } - fn generator(&mut self, g: &Generator) -> f32 { - let c = self.coords(); - let s = match g.kind { - GeneratorKind::EdgeWear => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, - GeneratorKind::Curvature => self.baked(BakedMap::Curvature).unwrap_or(0.5), - GeneratorKind::Dirt => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - GeneratorKind::AmbientOcclusion => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - GeneratorKind::ThinAreas => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0), - GeneratorKind::Position => c.pos.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, - GeneratorKind::Direction => c.nrm.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let coords = self.coords(); + let signal = match (generator.kind, &generator.detail) { + (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => self.curvature_detail(detail, curvature_sizes), + (GeneratorKind::EdgeWear, None) => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.baked(BakedMap::Curvature).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::ThinAreas, _) => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0), + (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, }; - let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s }; - let th = 1.0 - g.level.clamp(0.0, 1.0); - let soft = g.softness.max(1e-3); - let t = ((s - (th - soft)) / (2.0 * soft)).clamp(0.0, 1.0); - let v = t * t * (3.0 - 2.0 * t); - if g.invert { 1.0 - v } else { v } + let signal = if generator.noise_amount > 0.0 { + signal + (world_noise(coords.pos, generator.noise_scale, generator.seed) - 0.5) * generator.noise_amount + } else { + signal + }; + + // A smooth step from black to white over 2 × softness around 1 − level + let threshold = 1.0 - generator.level.clamp(0.0, 1.0); + let softness = generator.softness.max(1e-3); + let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0); + let value = ramp * ramp * (3.0 - 2.0 * ramp); + if generator.invert { 1.0 - value } else { value } } - fn mask(&mut self, m: &MaskPlan) -> f32 { - let mut v = m.background; - let mut skip = 0; - if let Some((k, field)) = m.start - && let Some(f) = field.get(self.x, self.y).and_then(|d| d.first().copied()) - { - v = f; - skip = k + 1; + /// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend. + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let Some(curvature) = self.baked(BakedMap::Curvature) else { return 0.0 }; + + let working_size = (self.res, self.inp.gbuf.height); + let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; + let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return 0.0 }; + + let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); + let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); + let blurred = |index: usize| curvature_sizes.and_then(|sizes| sizes.levels.get(index)).map_or(0.0, |level| level.sample(baked_x, baked_y)); + let (mut edges, mut cavities) = (0.0f32, 0.0f32); + for (index, (size, weight)) in CurvatureDetail::SIZES.iter().zip(detail.weights).enumerate() { + let deviation = if index == 0 { curvature - 0.5 } else { blurred(index - 1) }; + + let response = deviation * if *size == 0.0 { MAP_GAIN } else { GAIN_PER_DETAIL_TEXEL * size }; + let weight = weight.clamp(0.0, 1.0); + edges = 1.0 - (1.0 - edges) * (1.0 - weight * response.clamp(0.0, 1.0)); + cavities = 1.0 - (1.0 - cavities) * (1.0 - weight * (-response).clamp(0.0, 1.0)); } - for e in m.effects.iter().skip(skip) { - let o = e.opacity.clamp(0.0, 1.0); - match e.kind { + + match detail.mode { + CurvatureMode::Edges => edges, + CurvatureMode::Cavities => cavities, + CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), + CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + } + } + + fn mask(&mut self, plan: &MaskPlan) -> f32 { + let mut value = plan.background; + let mut skip = 0; + if let Some((filtered_index, field)) = plan.start + && let Some(filtered) = field.get(self.x, self.y).and_then(|texel| texel.first().copied()) + { + value = filtered; + skip = filtered_index + 1; + } + + for effect in plan.effects.iter().skip(skip) { + let opacity = effect.opacity.clamp(0.0, 1.0); + match effect.kind { EffectKind::Paint | EffectKind::Path(_) => { - let (mut pv, mut cov) = match e.data.as_deref() { - Some(d) => (from_u16(d.get(self.o * 2).copied().unwrap_or(0)), from_u16(d.get(self.o * 2 + 1).copied().unwrap_or(0))), + let (mut painted, mut cov) = match effect.data.as_deref() { + Some(data) => (from_u16(data.get(self.o * 2).copied().unwrap_or(0)), from_u16(data.get(self.o * 2 + 1).copied().unwrap_or(0))), None => (0.0, 0.0), }; - if e.preview - && let Some(p) = self.inp.preview + if effect.preview + && let Some(preview) = self.inp.preview { - let a = (self.stroke * p.opacity).clamp(0.0, 1.0); - if p.erase { - pv *= 1.0 - a; - cov *= 1.0 - a; + let stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0); + if preview.erase { + painted *= 1.0 - stroke; + cov *= 1.0 - stroke; } else { - pv = p.mask_value * a + pv * (1.0 - a); - cov = a + cov * (1.0 - a); + painted = preview.mask_value * stroke + painted * (1.0 - stroke); + cov = stroke + cov * (1.0 - stroke); } } if cov > 0.0 { - let val = pv / cov.max(1e-5); - v += (blend1(e.blend, v, val) - v) * cov * o; + let layer_value = painted / cov.max(1e-5); + value += (blend1(effect.blend, value, layer_value) - value) * cov * opacity; } } EffectKind::Fill { source, projection } => { - let val = self.source(source, projection, ChannelKind::Scalar)[0]; - v += (blend1(e.blend, v, val) - v) * o * self.cover(std::iter::once(source), projection); + let fill = self.source(source, projection, ChannelKind::Scalar)[0]; + value += (blend1(effect.blend, value, fill) - value) * opacity * self.cover(std::iter::once(source), projection); } - EffectKind::Generator(g) => { - let val = self.generator(g); - v += (blend1(e.blend, v, val) - v) * o; + EffectKind::Generator(generator) => { + let generated = self.generator(generator, effect.curvature_sizes.as_deref()); + value += (blend1(effect.blend, value, generated) - value) * opacity; } - EffectKind::Levels(l) => v += (l.apply(v) - v) * o, - EffectKind::Filter(f) => { - // A mask is gray (HSL only changes its lightness); neighbourhood filters come - // precomputed through `MaskPlan::start`. - let val = f.point(ChannelKind::Scalar, [v; 3]).map_or(v, |x| x[0]); - v += (val - v) * o; + EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, + EffectKind::Filter(filter) => { + // A mask is gray (HSL only changes its lightness); neighbourhood filters come precomputed through `MaskPlan::start` + let filtered = filter.point(ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]); + value += (filtered - value) * opacity; } EffectKind::ColorSelection { colors, tolerance } => { let id = self.baked_color(BakedMap::Id); - let hit = id.is_some_and(|c| colors.iter().any(|k| (k[0] - c[0]).abs().max((k[1] - c[1]).abs()).max((k[2] - c[2]).abs()) <= *tolerance)); - let val = if hit { 1.0 } else { 0.0 }; - v += (blend1(e.blend, v, val) - v) * o; + let within = |picked: &[f32; 3], color: [f32; 3]| (0..3).all(|component| (picked[component] - color[component]).abs() <= *tolerance); + let selected = if id.is_some_and(|color| colors.iter().any(|picked| within(picked, color))) { 1.0 } else { 0.0 }; + value += (blend1(effect.blend, value, selected) - value) * opacity; } - EffectKind::Compare { op, value, tolerance } => { + EffectKind::Compare { op, value: compared, tolerance } => { let pass = match op { - CompareOp::LesserThan => v < *value, - CompareOp::GreaterThan => v > *value, - CompareOp::WithinTolerance => (v - value).abs() <= *tolerance, + CompareOp::LesserThan => value < *compared, + CompareOp::GreaterThan => value > *compared, + CompareOp::WithinTolerance => (value - compared).abs() <= *tolerance, }; - let val = if pass { 1.0 } else { 0.0 }; - v += (val - v) * o; + let result = if pass { 1.0 } else { 0.0 }; + value += (result - value) * opacity; } - // Content-only effects. + // Content-only effects EffectKind::Material(_) | EffectKind::Anchor => {} } } - v.clamp(0.0, 1.0) + value.clamp(0.0, 1.0) } /// Composite `nodes` over `acc`, recording anchors. Returns true when it reached the `stop` @@ -2455,6 +2504,44 @@ mod tests { assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs"); } + #[test] + fn larger_curvature_detail_sizes_reach_further_from_an_edge() { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 256, 256); + fixture.project.texture_sets[0].resolution = 256; + let ridge: Vec = (0..256 * 256).map(|texel| if texel % 256 == 128 { 1.0 } else { 0.5 }).collect(); + fixture.baked = BakedMaps { resolution: 256, maps: [(BakedMap::Curvature, Arc::new(ridge))].into() }; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let row_with = |fixture: &mut Fixture, weights: [f32; 7]| -> Vec { + let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights }; + let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + let images = Default::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + block_scales: BlockScales::default(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, layer, &(120..137).map(|x| (x, 128)).collect::>()).unwrap() + }; + + // The row starts at x 120: the ridge is its ninth texel, five texels left of it the fourth + let (ridge, five_texels_away) = (8, 3); + let finest = row_with(&mut fixture, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + let largest = row_with(&mut fixture, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]); + assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}"); + assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}"); + } + #[test] fn blur_filter_softens_mask_edges() { let mut f = fixture(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 01365a27..fe57e611 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -9,6 +9,8 @@ mod baked_maps; pub mod below; +mod curvature_size_level; +pub mod curvature_sizes; pub mod display; pub mod eval; pub mod pattern; diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 551c9803..19c82f61 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -6,6 +6,12 @@ use serde::{Deserialize, Serialize}; use crate::{BlendMode, Channel, ChannelKind, lum}; +mod curvature_detail; +mod curvature_mode; + +pub use curvature_detail::CurvatureDetail; +pub use curvature_mode::CurvatureMode; + /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub struct LayerId(pub u64); @@ -540,17 +546,27 @@ pub struct Generator { /// Direction for `Position` / `Direction` generators (world space). pub direction: [f32; 3], pub invert: bool, + /// Mode and detail sizes of `Curvature` / `EdgeWear` generators (None: the curvature map as baked, as before detail sizes existed). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub detail: Option, } impl Generator { pub fn new(kind: GeneratorKind) -> Generator { let (level, softness, noise_amount) = match kind { - GeneratorKind::EdgeWear => (0.6, 0.12, 0.5), + GeneratorKind::EdgeWear => (0.5, 0.25, 0.3), + GeneratorKind::Curvature => (0.5, 0.5, 0.0), GeneratorKind::Dirt => (0.55, 0.25, 0.35), GeneratorKind::ThinAreas => (0.3, 0.2, 0.0), _ => (0.5, 0.25, 0.0), }; - Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false } + let detail = match kind { + GeneratorKind::Curvature => Some(CurvatureDetail::default()), + // Worn edges are thin lines: mostly the finer sizes + GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0] }), + _ => None, + }; + Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false, detail } } } @@ -1050,6 +1066,17 @@ impl Effect { mod tests { use super::*; + #[test] + fn curvature_generators_saved_before_detail_sizes_load_without_them() { + let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); + assert!(saved.get("detail").is_some(), "new curvature generators have detail sizes"); + + saved.as_object_mut().unwrap().remove("detail"); + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.detail, None); + assert_eq!(Generator::new(GeneratorKind::Dirt).detail, None, "only curvature and edge wear generators have detail sizes"); + } + #[test] fn levels_map_range_and_gamma() { let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 }; diff --git a/crates/core/src/layer/curvature_detail.rs b/crates/core/src/layer/curvature_detail.rs new file mode 100644 index 00000000..f843eac9 --- /dev/null +++ b/crates/core/src/layer/curvature_detail.rs @@ -0,0 +1,22 @@ +use serde::{Deserialize, Serialize}; + +use super::curvature_mode::CurvatureMode; + +/// How a curvature generator reads the curvature map: its mode and how much each detail size adds. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CurvatureDetail { + pub mode: CurvatureMode, + /// Weight (0..1) of each size in [`CurvatureDetail::SIZES`], finest first. + pub weights: [f32; CurvatureDetail::SIZES.len()], +} + +impl CurvatureDetail { + /// Detail sizes as blur radii in texels at 2K: the map itself, then doubling radii. + pub const SIZES: [f32; 7] = [0.0, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0]; +} + +impl Default for CurvatureDetail { + fn default() -> Self { + CurvatureDetail { mode: CurvatureMode::Edges, weights: [1.0, 0.85, 0.7, 0.55, 0.4, 0.25, 0.15] } + } +} diff --git a/crates/core/src/layer/curvature_mode.rs b/crates/core/src/layer/curvature_mode.rs new file mode 100644 index 00000000..a4183e7a --- /dev/null +++ b/crates/core/src/layer/curvature_mode.rs @@ -0,0 +1,34 @@ +use serde::{Deserialize, Serialize}; + +/// Which side of the curvature map a curvature generator shows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum CurvatureMode { + /// Convex edges white. + #[default] + Edges, + /// Concave cavities white. + Cavities, + /// Edges and cavities both white. + Both, + /// Signed curvature around mid gray (cavities dark, edges light). + Raw, +} + +impl CurvatureMode { + pub const ALL: [CurvatureMode; 4] = [CurvatureMode::Edges, CurvatureMode::Cavities, CurvatureMode::Both, CurvatureMode::Raw]; + + pub fn label(self) -> &'static str { + match self { + CurvatureMode::Edges => "Edges", + CurvatureMode::Cavities => "Cavities", + CurvatureMode::Both => "Edges and cavities", + CurvatureMode::Raw => "Raw curvature", + } + } + + /// The mode named `name` (its variant or label, any case). + pub fn parse(name: &str) -> Option { + let normalized = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], ""); + CurvatureMode::ALL.into_iter().find(|mode| normalized(&format!("{mode:?}")) == normalized(name) || normalized(mode.label()) == normalized(name)) + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 72adf044..75ea2405 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -24,8 +24,9 @@ pub use bake::{ pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ - ChannelBlend, CompareOp, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, - LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit, + ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, + LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, + hsl_adjust, per_unit, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 347b7390..ae73a3a7 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -2,7 +2,7 @@ //! without a screenshot. use serde_json::{Value, json}; -use texturecraft_core::{Effect, EffectKind, Fill, Filter, Layer, LayerKind, NormalFormat, Projection, Source}; +use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Source}; use crate::Session; use crate::session::StackTarget; @@ -34,38 +34,45 @@ fn fill_json(f: &Fill) -> Value { } /// A mask or content (`content`) effect. -fn effect_json(s: &Session, e: &Effect, content: bool) -> Value { - let mut ej = json!({ "id": e.id.0, "name": e.name, "kind": e.kind.name(), "visible": e.visible, "blend": e.blend.label(), "opacity": e.opacity }); - match &e.kind { - EffectKind::Generator(g) => { - ej["generator"] = json!({ "type": format!("{:?}", g.kind), "level": g.level, "softness": g.softness, "noise": g.noise_amount, "invert": g.invert }) - } - EffectKind::Levels(lv) => ej["levels"] = json!([lv.in_low, lv.in_high, lv.gamma, lv.out_low, lv.out_high]), +fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { + let mut out = json!({ "id": effect.id.0, "name": effect.name, "kind": effect.kind.name(), "visible": effect.visible, "blend": effect.blend.label(), "opacity": effect.opacity }); + let mask_tiles = || session.doc.pixels.masks.get(&effect.id).map_or(0, |image| image.allocated_count()); + let content_tiles = || session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == effect.id).map(|(_, image)| image.allocated_count()).sum::(); + + match &effect.kind { + EffectKind::Generator(generator) => out["generator"] = generator_json(generator), + EffectKind::Levels(levels) => out["levels"] = json!([levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]), EffectKind::Path(paths) => { - ej["paths"] = json!(paths.iter().map(|p| json!({ "points": p.points.len(), "uv": p.uv, "closed": p.closed, "fill": p.fill })).collect::>()); - ej["tiles"] = json!(if content { - s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::() - } else { - s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0) - }); + out["paths"] = json!( + paths.iter().map(|path| json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill })).collect::>() + ); + out["tiles"] = json!(if content { content_tiles() } else { mask_tiles() }); } - EffectKind::Paint if content => { - ej["tiles"] = json!(s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::()) - } - EffectKind::Paint => ej["tiles"] = json!(s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0)), - EffectKind::Fill { source, .. } => ej["source"] = source_json(source), - EffectKind::Material(f) => ej["fill"] = fill_json(f), - EffectKind::Filter(f) => { - ej["filter"] = json!(f); - match f { - Filter::Hsl { hue, saturation, lightness } => ej["hsl"] = json!([hue, saturation, lightness]), - Filter::Blur { radius } => ej["radius"] = json!(radius), + EffectKind::Paint if content => out["tiles"] = json!(content_tiles()), + EffectKind::Paint => out["tiles"] = json!(mask_tiles()), + EffectKind::Fill { source, .. } => out["source"] = source_json(source), + EffectKind::Material(fill) => out["fill"] = fill_json(fill), + EffectKind::Filter(filter) => { + out["filter"] = json!(filter); + match filter { + Filter::Hsl { hue, saturation, lightness } => out["hsl"] = json!([hue, saturation, lightness]), + Filter::Blur { radius } => out["radius"] = json!(radius), _ => {} } } _ => {} } - ej + out +} + +/// A generator's settings, with its curvature mode and detail size weights when it has them. +fn generator_json(generator: &Generator) -> Value { + let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "invert": generator.invert }); + if let Some(detail) = &generator.detail { + out["mode"] = json!(format!("{:?}", detail.mode)); + out["sizes"] = json!(detail.weights); + } + out } fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value { diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 2656bd15..41cecca8 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -2,8 +2,8 @@ use serde_json::{Value, json}; use texturecraft_core::{ - BlendMode, Channel, CompareOp, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, Procedural, ProceduralKind, - Project, Source, + BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, + Procedural, ProceduralKind, Project, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?}", + "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", has_layer, add_generator ), @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", has_layer, set ), @@ -314,39 +314,67 @@ fn add_fill(s: &mut Session, p: &Value) -> Result { push_effect(s, p, EffectKind::Fill { source, projection }, blend) } -fn generator_from(p: &Value, g: &mut Generator) { - if let Some(v) = f32p(p, "level") { - g.level = v.clamp(0.0, 1.0); +/// Apply the generator parameters in `params` to `generator` (`command` names it in errors). +fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + if let Some(level) = f32p(params, "level") { + generator.level = level.clamp(0.0, 1.0); } - if let Some(v) = f32p(p, "softness") { - g.softness = v.clamp(0.0, 1.0); + if let Some(softness) = f32p(params, "softness") { + generator.softness = softness.clamp(0.0, 1.0); } - if let Some(v) = f32p(p, "noise") { - g.noise_amount = v.clamp(0.0, 2.0); + if let Some(noise) = f32p(params, "noise") { + generator.noise_amount = noise.clamp(0.0, 2.0); } - if let Some(v) = f32p(p, "noiseScale") { - g.noise_scale = v.clamp(0.01, 1000.0); + if let Some(noise_scale) = f32p(params, "noiseScale") { + generator.noise_scale = noise_scale.clamp(0.01, 1000.0); } - if let Some(v) = u64p(p, "seed") { - g.seed = v as u32; + if let Some(seed) = u64p(params, "seed") { + generator.seed = seed as u32; } - if let Some(v) = boolp(p, "invert") { - g.invert = v; + if let Some(invert) = boolp(params, "invert") { + generator.invert = invert; } - if let Some(d) = color_param(p, "direction") { - g.direction = d; + if let Some(direction) = color_param(params, "direction") { + generator.direction = direction; } + + // A mode or sizes also give a curvature generator saved before detail sizes its detail + let mode = + strp(params, "mode").map(|name| CurvatureMode::parse(name).ok_or_else(|| bad(command, format!("unknown curvature mode `{name}`")))).transpose()?; + let weights = params.get("sizes").map(|value| size_weights(command, value)).transpose()?; + if mode.is_none() && weights.is_none() { + return Ok(()); + } + if !matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { + return Err(bad(command, "only curvature and edge wear generators have a mode and detail sizes")); + } + + let detail = generator.detail.get_or_insert_with(CurvatureDetail::default); + if let Some(mode) = mode { + detail.mode = mode; + } + if let Some(weights) = weights { + detail.weights = weights; + } + Ok(()) } -fn add_generator(s: &mut Session, p: &Value) -> Result { - let kind = match strp(p, "generator") { - Some(k) => GeneratorKind::parse(k).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{k}`")))?, +/// The detail size weights in `value`: one number (0..1) per size of [`CurvatureDetail::SIZES`], finest first. +fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::SIZES.len()]> { + let weights: Vec = + value.as_array().map(|items| items.iter().filter_map(Value::as_f64).map(|weight| (weight as f32).clamp(0.0, 1.0)).collect()).unwrap_or_default(); + weights.try_into().map_err(|_| bad(command, format!("`sizes` takes {} numbers, finest first", CurvatureDetail::SIZES.len()))) +} + +fn add_generator(session: &mut Session, params: &Value) -> Result { + let kind = match strp(params, "generator") { + Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?, None => GeneratorKind::EdgeWear, }; - let mut g = Generator::new(kind); - generator_from(p, &mut g); - let blend = blend_param("effect.add.generator", p, "blend")?.unwrap_or(BlendMode::Normal); - push_effect(s, p, EffectKind::Generator(g), blend) + let mut generator = Generator::new(kind); + generator_from("effect.add.generator", params, &mut generator)?; + let blend = blend_param("effect.add.generator", params, "blend")?.unwrap_or(BlendMode::Normal); + push_effect(session, params, EffectKind::Generator(generator), blend) } pub(crate) fn levels_from(p: &Value, l: &mut Levels) { @@ -413,55 +441,57 @@ fn histogram(s: &mut Session, p: &Value) -> Result { Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) }) } -fn set(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(s, p, "effect.set")?; - let blend = blend_param("effect.set", p, "blend")?; - // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone - // re-targets the current one. - let anchor = match s.doc.project.effect(eid) { +fn set(session: &mut Session, params: &Value) -> Result { + let target = effect_id(session, params, "effect.set")?; + let blend = blend_param("effect.set", params, "blend")?; + + // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone re-targets the current one + let anchor = match session.doc.project.effect(target) { Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => { let (current, channel) = match source { Source::Anchor { anchor, channel } => (Some(*anchor), *channel), _ => (None, Channel::Height), }; - let channel_param = channel_param("effect.set", p, "anchorChannel")?; - match u64p(p, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) { - Some(a) => Some(anchor_source(s, "effect.set", owner, a, channel_param.unwrap_or(channel))?), + let channel_param = channel_param("effect.set", params, "anchorChannel")?; + match u64p(params, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) { + Some(anchor) => Some(anchor_source(session, "effect.set", owner, anchor, channel_param.unwrap_or(channel))?), None => None, } } _ => None, }; - s.edit("Edit effect", |s| { - let e = s.doc.project.effect_mut(eid).ok_or_else(|| bad("effect.set", format!("no effect {}", eid.0)))?; - if let Some(v) = boolp(p, "visible") { - e.visible = v; + + session.edit("Edit effect", |session| { + let effect = session.doc.project.effect_mut(target).ok_or_else(|| bad("effect.set", format!("no effect {}", target.0)))?; + if let Some(visible) = boolp(params, "visible") { + effect.visible = visible; } - if let Some(b) = blend { - e.blend = b; + if let Some(blend) = blend { + effect.blend = blend; } - if let Some(o) = f32p(p, "opacity") { - e.opacity = o.clamp(0.0, 1.0); + if let Some(opacity) = f32p(params, "opacity") { + effect.opacity = opacity.clamp(0.0, 1.0); } - if let Some(n) = name_param(p) { - e.name = n.to_string(); + if let Some(name) = name_param(params) { + effect.name = name.to_string(); } - match &mut e.kind { - EffectKind::Generator(g) => generator_from(p, g), - EffectKind::Levels(l) => levels_from(p, l), - EffectKind::Filter(f) => crate::filter_lib::apply(p, f, "effect.set")?, + + match &mut effect.kind { + EffectKind::Generator(generator) => generator_from("effect.set", params, generator)?, + EffectKind::Levels(levels) => levels_from(params, levels), + EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, "effect.set")?, EffectKind::Fill { source, .. } => { - if let Some(a) = anchor { - *source = a; - } else if let Some(x) = f32p(p, "value") + if let Some(anchor) = anchor { + *source = anchor; + } else if let Some(value) = f32p(params, "value") && matches!(source, Source::Uniform(_) | Source::Anchor { .. }) { - *source = Source::Uniform([x.clamp(0.0, 1.0); 3]); + *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } } EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => { - if let Some(x) = f32p(p, "tolerance") { - *tolerance = x.clamp(0.0, 1.0); + if let Some(value) = f32p(params, "tolerance") { + *tolerance = value.clamp(0.0, 1.0); } } _ => {} diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 5038abbb..dd0111f3 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -62,14 +62,14 @@ pub fn find(name: &str) -> Option<&'static SmartMask> { const UP: [f32; 3] = [0.0, 1.0, 0.0]; -/// A mesh-map generator with explicit threshold, softness and noise breakup. +/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes). pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, ..Generator::new(kind) }) } /// A direction or position generator (`invert` flips the result). pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, softness: f32, noise: f32, invert: bool) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, ..Generator::new(kind) }) } /// A triplanar grayscale pattern fill. diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 02be7a8d..e7e38614 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -380,3 +380,23 @@ fn background_resizes_match_the_command_and_keep_later_edits() { b.update(); assert_eq!(b.caches[0].size, (512, 512)); } + +#[test] +fn curvature_generators_take_a_mode_and_detail_sizes() { + let mut state = session(); + execute(&mut state, "layer.add.fill", &json!({})).unwrap(); + execute(&mut state, "mask.add.black", &Value::Null).unwrap(); + let added = execute(&mut state, "effect.add.generator", &json!({"generator": "curvature", "mode": "cavities"})).unwrap(); + let effect = added["effect"].clone(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5]})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""mode":"Cavities""#) && inspect.contains(r#""sizes":[0.0,0.0,0.0,1.0,0.0,0.0,0.5]"#), "{inspect}"); + + let too_few = execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [1.0, 0.5]})); + assert!(too_few.is_err(), "sizes takes one weight per detail size"); + let unknown = execute(&mut state, "effect.set", &json!({"effect": effect, "mode": "ridges"})); + assert!(unknown.is_err(), "unknown modes are rejected"); + let dirt = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt", "mode": "edges"})); + assert!(dirt.is_err(), "only curvature generators have a mode"); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 976a3035..55e9e8f3 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -5,8 +5,8 @@ use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, - Projection, Source, + BakedMap, BlendMode, Channel, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind, + LinkParam, MaterialLink, ProceduralKind, Projection, Source, }; use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; use texturecraft_engine::paint::{BrushAlpha, alphas}; @@ -1873,63 +1873,42 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId) { let tk = Tokens::get(ui.ctx()); - let Some((_, e)) = app.session.doc.project.effect(eid).map(|(l, e)| (l, e.clone())) else { return }; + let Some((_, effect)) = app.session.doc.project.effect(eid).map(|(owner, effect)| (owner, effect.clone())) else { return }; + let id = eid.0; ui.horizontal(|ui| { ui.label(tr("Blending")); - egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(e.blend.label())).show_ui(ui, |ui| { - for m in BlendMode::all() { - if ui.selectable_label(m == e.blend, tr(m.label())).clicked() { - app.run("effect.set", json!({"effect": id, "blend": format!("{m:?}")})); + egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(effect.blend.label())).show_ui(ui, |ui| { + for mode in BlendMode::all() { + if ui.selectable_label(mode == effect.blend, tr(mode.label())).clicked() { + app.run("effect.set", json!({"effect": id, "blend": format!("{mode:?}")})); } } }); }); - let mut op = e.opacity; - if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut op, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "opacity": op, "merge": merge})); + let mut opacity = effect.opacity; + if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut opacity, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "opacity": opacity, "merge": merge})); } ui.separator(); - match &e.kind { - EffectKind::Generator(g) => { - ui.label(caption(tr("Generator"))); - egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(g.kind.label())).show_ui(ui, |ui| { - for k in GeneratorKind::ALL { - if ui.selectable_label(k == g.kind, tr(k.label())).clicked() { - // Replace the generator kind: remove and add keeps ordering simple. - app.run("effect.remove", json!({"effect": id})); - app.run("effect.add.generator", json!({"generator": format!("{k:?}")})); - } - } - }); - let (mut level, mut soft, mut noise, mut ns) = (g.level, g.softness, g.noise_amount, g.noise_scale); - let r1 = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); - let r2 = slider_edit(ui, tr("Softness"), &mut soft, 0.0..=1.0, 2); - let r3 = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); - let r4 = slider_edit(ui, tr("Noise scale"), &mut ns, 0.1..=64.0, 1); - let mut inv = g.invert; - let r5 = ui.checkbox(&mut inv, tr("Invert")); - if let Some(merge) = r1.or(r2).or(r3).or(r4).or(r5.changed().then_some(false)) { - app.run("effect.set", json!({"effect": id, "level": level, "softness": soft, "noise": noise, "noiseScale": ns, "invert": inv, "merge": merge})); - } - if !app.session.doc.baked.contains_key(&app.session.ts()) { - ui.label( - RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning), - ); - } - } - EffectKind::Levels(l) => { + + match &effect.kind { + EffectKind::Generator(generator) => generator_properties(app, ui, id, generator), + EffectKind::Levels(levels) => { ui.label(caption(tr("Levels"))); - levels_histogram(app, ui, layer, eid, (l.in_low, l.in_high)); - let mut v = [l.in_low, l.in_high, l.gamma, l.out_low, l.out_high]; + levels_histogram(app, ui, layer, eid, (levels.in_low, levels.in_high)); + let mut values = [levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]; let labels = [tr("Input low"), tr("Input high"), tr("Gamma"), tr("Output low"), tr("Output high")]; let mut edit = None; - for (i, label) in labels.iter().enumerate() { - let range = if i == 2 { 0.1..=5.0 } else { 0.0..=1.0 }; - edit = edit.or(slider_edit(ui, label, &mut v[i], range, 2)); + for (index, label) in labels.iter().enumerate() { + let range = if index == 2 { 0.1..=5.0 } else { 0.0..=1.0 }; + edit = edit.or(slider_edit(ui, label, &mut values[index], range, 2)); } if let Some(merge) = edit { - app.run("effect.set", json!({"effect": id, "inLow": v[0], "inHigh": v[1], "gamma": v[2], "outLow": v[3], "outHigh": v[4], "merge": merge})); + app.run( + "effect.set", + json!({"effect": id, "inLow": values[0], "inHigh": values[1], "gamma": values[2], "outLow": values[3], "outHigh": values[4], "merge": merge}), + ); } } EffectKind::Fill { source, .. } => { @@ -1945,25 +1924,25 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() { app.run("effect.set", json!({"effect": id, "value": 1.0})); } - for (a, label) in &anchors { - if ui.selectable_label(source.anchor() == Some(*a), trf("Anchor: {name}", &[("name", label)])).clicked() { - app.run("effect.set", json!({"effect": id, "anchor": a.0})); + for (anchor, label) in &anchors { + if ui.selectable_label(source.anchor() == Some(*anchor), trf("Anchor: {name}", &[("name", label)])).clicked() { + app.run("effect.set", json!({"effect": id, "anchor": anchor.0})); } } }); match source { - Source::Uniform(v) => { - let mut x = v[0]; - if let Some(merge) = slider_edit(ui, tr("Value"), &mut x, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "value": x, "merge": merge})); + Source::Uniform(color) => { + let mut value = color[0]; + if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "value": value, "merge": merge})); } } Source::Anchor { channel, .. } => { - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); combo(ui, tr("Channel"), tr(channel.label()), |ui| { - for c in chans { - if ui.selectable_label(c == *channel, tr(c.label())).clicked() { - app.run("effect.set", json!({"effect": id, "anchorChannel": c.id()})); + for option in channels { + if ui.selectable_label(option == *channel, tr(option.label())).clicked() { + app.run("effect.set", json!({"effect": id, "anchorChannel": option.id()})); } } }); @@ -1975,10 +1954,10 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tk.text_dim)); } } - EffectKind::Material(f) => { + EffectKind::Material(fill) => { ui.label(caption(tr("Fill"))); - let on: Vec = f.sources.keys().copied().collect(); - fill_editor(app, ui, f, &json!({"effect": id}), &on, layer.id); + let enabled: Vec = fill.sources.keys().copied().collect(); + fill_editor(app, ui, fill, &json!({"effect": id}), &enabled, layer.id); } EffectKind::Anchor => { ui.label(caption(tr("Anchor point"))); @@ -1988,7 +1967,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ); } EffectKind::Paint => { - let hint = if layer.content_effects.iter().any(|x| x.id == eid) { + let hint = if layer.content_effects.iter().any(|content| content.id == eid) { tr("Paint on the mesh to edit the layer content.") } else { tr("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.") @@ -2002,30 +1981,102 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: .color(tk.text_dim), ); let editing = app.session.tool.path.editing; - for i in 0..paths.len() { + for index in 0..paths.len() { ui.horizontal(|ui| { - let on = editing == Some((eid, i)); - if ui.selectable_label(on, format!("{} {}", tr("Path"), i + 1)).on_hover_text(tr("Edit")).clicked() { - if on { + let selected = editing == Some((eid, index)); + if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() { + if selected { app.run("tool.path", json!({"clear": true})); } else { - app.run("path.edit", json!({"effect": id, "index": i})); + app.run("path.edit", json!({"effect": id, "index": index})); } } if icon_button(ui, ic::TRASH, tr("Remove"), false, 22.0).clicked() { - app.run("path.remove", json!({"effect": id, "index": i})); + app.run("path.remove", json!({"effect": id, "index": index})); } }); } tool_properties(app, ui); } - EffectKind::Filter(f) => filter_properties(app, ui, id, f), + EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), other => { ui.label(RichText::new(tr(other.name())).color(tk.text_dim)); } } } +/// The settings of generator effect `id`. +fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let tk = Tokens::get(ui.ctx()); + ui.label(caption(tr("Generator"))); + egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { + for kind in GeneratorKind::ALL { + if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() { + // Replace the generator kind: remove and add keeps ordering simple + app.run("effect.remove", json!({"effect": id})); + app.run("effect.add.generator", json!({"generator": format!("{kind:?}")})); + } + } + }); + + let (mut level, mut softness, mut noise, mut noise_scale, mut invert) = + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.invert); + let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); + let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); + let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); + let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); + let invert_edit = ui.checkbox(&mut invert, tr("Invert")).changed().then_some(false); + if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(invert_edit) { + app.run( + "effect.set", + json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "invert": invert, "merge": merge}), + ); + } + + if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } + if !app.session.doc.baked.contains_key(&app.session.ts()) { + ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning)); + } +} + +/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). +fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { + let tk = Tokens::get(ui.ctx()); + let shown = detail.cloned().unwrap_or_default(); + combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { + for mode in CurvatureMode::ALL { + if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() { + app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); + } + } + }); + + ui.label(caption(tr("Detail sizes"))); + let mut weights = shown.weights; + let mut edit = None; + for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { + edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); + } + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); + } + if detail.is_none() { + ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tk.text_dim)); + } +} + +/// The translated name of curvature mode `mode`. +fn curvature_mode_label(mode: CurvatureMode) -> &'static str { + match mode { + CurvatureMode::Edges => tr("Edges"), + CurvatureMode::Cavities => tr("Cavities"), + CurvatureMode::Both => tr("Edges and cavities"), + CurvatureMode::Raw => tr("Raw curvature"), + } +} + /// The histogram of what levels effect `eid` of `layer` remaps (its mask, or a content channel /// picked here), with the input range marked. Recomputed after a document change once no /// pointer button is held, so dragging a slider keeps the last one. diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..a76cabf0 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1035,4 +1035,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Edges", "الحواف"), + ("Cavities", "التجاويف"), + ("Edges and cavities", "الحواف والتجاويف"), + ("Raw curvature", "الانحناء الخام"), + ("Detail sizes", "أحجام التفاصيل"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "يقرأ خريطة الانحناء كما خُبزت: تغيير الوضع أو أحد الأحجام يفعّل أحجام التفاصيل.", + ), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..7135f142 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1078,4 +1078,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Auflösungsüberschreibung entfernen"), ("Texture set resolution", "Auflösung des Textursets"), ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ("Edges", "Kanten"), + ("Cavities", "Vertiefungen"), + ("Edges and cavities", "Kanten und Vertiefungen"), + ("Raw curvature", "Rohe Krümmung"), + ("Detail sizes", "Detailgrößen"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Liest die Krümmungskarte wie gebacken: Eine Änderung des Modus oder einer Größe schaltet die Detailgrößen ein.", + ), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..3c5e03ec 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1063,4 +1063,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Quitar resolución personalizada"), ("Texture set resolution", "Resolución del conjunto de texturas"), ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ("Edges", "Bordes"), + ("Cavities", "Cavidades"), + ("Edges and cavities", "Bordes y cavidades"), + ("Raw curvature", "Curvatura sin procesar"), + ("Detail sizes", "Tamaños de detalle"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lee el mapa de curvatura tal como se horneó: cambiar el modo o un tamaño activa los tamaños de detalle.", + ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..1c55b5ee 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1087,4 +1087,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Supprimer la résolution personnalisée"), ("Texture set resolution", "Résolution de l'ensemble de textures"), ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ("Edges", "Arêtes"), + ("Cavities", "Cavités"), + ("Edges and cavities", "Arêtes et cavités"), + ("Raw curvature", "Courbure brute"), + ("Detail sizes", "Tailles de détail"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lit la carte de courbure telle que calculée : changer le mode ou une taille active les tailles de détail.", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..a84b16d1 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1072,4 +1072,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Rimuovi risoluzione personalizzata"), ("Texture set resolution", "Risoluzione del set di texture"), ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ("Edges", "Bordi"), + ("Cavities", "Cavità"), + ("Edges and cavities", "Bordi e cavità"), + ("Raw curvature", "Curvatura grezza"), + ("Detail sizes", "Dimensioni del dettaglio"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Legge la mappa di curvatura così come è stata calcolata: cambiare la modalità o una dimensione attiva le dimensioni del dettaglio.", + ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..3f2fa7e6 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1057,4 +1057,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Edges", "エッジ"), + ("Cavities", "くぼみ"), + ("Edges and cavities", "エッジとくぼみ"), + ("Raw curvature", "生の曲率"), + ("Detail sizes", "ディテールサイズ"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "曲率マップをベイクされたまま読み取ります。モードやサイズを変更するとディテールサイズが有効になります。", + ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..e0513259 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1045,4 +1045,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Edges", "가장자리"), + ("Cavities", "오목한 부분"), + ("Edges and cavities", "가장자리와 오목한 부분"), + ("Raw curvature", "원시 곡률"), + ("Detail sizes", "디테일 크기"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "곡률 맵을 베이크된 그대로 읽습니다. 모드나 크기를 바꾸면 디테일 크기가 켜집니다.", + ), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..65e55fa2 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1060,4 +1060,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Remover resolução personalizada"), ("Texture set resolution", "Resolução do conjunto de texturas"), ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ("Edges", "Bordas"), + ("Cavities", "Cavidades"), + ("Edges and cavities", "Bordas e cavidades"), + ("Raw curvature", "Curvatura bruta"), + ("Detail sizes", "Tamanhos de detalhe"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lê o mapa de curvatura como foi assado: mudar o modo ou um tamanho ativa os tamanhos de detalhe.", + ), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..e41e91d4 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1003,4 +1003,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Edges", "边缘"), + ("Cavities", "凹陷"), + ("Edges and cavities", "边缘和凹陷"), + ("Raw curvature", "原始曲率"), + ("Detail sizes", "细节尺寸"), + ("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", "按烘焙原样读取曲率贴图:更改模式或尺寸会启用细节尺寸。"), ]; From 906dcf324e2ed8de2f72cd630ec992fa0324aceb Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 01:17:47 +0000 Subject: [PATCH 42/73] Curvature detail: name the tuned weights, clean up the effect plans and blur --- crates/compose/src/eval.rs | 38 +++++++++++------------ crates/core/src/layer.rs | 3 +- crates/core/src/layer/curvature_detail.rs | 8 ++++- 3 files changed, 27 insertions(+), 22 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 412cfe58..1eb29882 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -432,15 +432,15 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 /// the region it is computed in, so tiles composited in any grouping agree exactly. const FIX: f64 = (1u64 << 24) as f64; -/// Three running-sum box blurs (≈ Gaussian) of a `w × h` image along rows then along columns. -/// Rows (and columns, transposed) blur in parallel. -pub(crate) fn blur(data: &mut [f32], w: usize, h: usize, r: usize) { - let fix = |v: &f32| if v.is_finite() { (f64::from(v.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; - let mut v: Vec = data.par_iter().map(fix).collect(); - blur_rows(&mut v, w, r); - let mut t = transpose(&v, w, h); - blur_rows(&mut t, h, r); - data.par_iter_mut().zip(transpose(&t, h, w)).for_each(|(d, s)| *d = (s as f64 / FIX) as f32); +/// Three running-sum box blurs (≈ Gaussian) of a `width × height` image along its rows, then its columns, each in parallel. +pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) { + let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; + let mut fixed: Vec = data.par_iter().map(to_fixed).collect(); + blur_rows(&mut fixed, width, radius); + + let mut columns = transpose(&fixed, width, height); + blur_rows(&mut columns, height, radius); + data.par_iter_mut().zip(transpose(&columns, height, width)).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32); } /// Three box blurs of radius `r` along every row (`w` long) of `data`. @@ -813,18 +813,18 @@ struct Node<'a> { fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, channel: Option) -> Vec> { effects .iter() - .filter(|e| e.visible) - .map(|e| { - let (img, target) = match channel { - Some(c) => (inp.pixels.layer(e.id, c), PaintTarget::Layer(e.id)), - None => (inp.pixels.masks.get(&e.id), PaintTarget::Mask(e.id)), + .filter(|effect| effect.visible) + .map(|effect| { + let (image, target) = match channel { + Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), + None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; - let reads_detail = matches!(&e.kind, EffectKind::Generator(generator) if generator.detail.is_some()); + let reads_detail = matches!(&effect.kind, EffectKind::Generator(generator) if generator.detail.is_some()); EffectPlan { - kind: &e.kind, - blend: e.blend, - opacity: e.opacity, - data: if e.kind.painted() { tile_of(inp, img, tx, ty, channel) } else { None }, + kind: &effect.kind, + blend: effect.blend, + opacity: effect.opacity, + data: if effect.kind.painted() { tile_of(inp, image, tx, ty, channel) } else { None }, preview: previews(inp, target), curvature_sizes: if reads_detail { CurvatureSizes::of(inp) } else { None }, } diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 19c82f61..37ce47e8 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -562,8 +562,7 @@ impl Generator { }; let detail = match kind { GeneratorKind::Curvature => Some(CurvatureDetail::default()), - // Worn edges are thin lines: mostly the finer sizes - GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0] }), + GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }), _ => None, }; Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false, detail } diff --git a/crates/core/src/layer/curvature_detail.rs b/crates/core/src/layer/curvature_detail.rs index f843eac9..826b9823 100644 --- a/crates/core/src/layer/curvature_detail.rs +++ b/crates/core/src/layer/curvature_detail.rs @@ -13,10 +13,16 @@ pub struct CurvatureDetail { impl CurvatureDetail { /// Detail sizes as blur radii in texels at 2K: the map itself, then doubling radii. pub const SIZES: [f32; 7] = [0.0, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0]; + + /// Weights falling off with size, tuned by eye on hard-surface bakes: sharp edges first, broad shapes lit faintly. + pub const BROAD_WEIGHTS: [f32; 7] = [1.0, 0.85, 0.7, 0.55, 0.4, 0.25, 0.15]; + + /// Mostly the finer sizes, tuned the same way: worn edges are thin lines. + pub const EDGE_WEIGHTS: [f32; 7] = [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0]; } impl Default for CurvatureDetail { fn default() -> Self { - CurvatureDetail { mode: CurvatureMode::Edges, weights: [1.0, 0.85, 0.7, 0.55, 0.4, 0.25, 0.15] } + CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::BROAD_WEIGHTS } } } From 1a0fc5fec8d28085d2b0b17630d63e3cb2fe3481 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 11:51:43 +0000 Subject: [PATCH 43/73] Curvature detail: build only the sizes in use, map coverage on all cores --- crates/compose/src/curvature_sizes.rs | 160 ++++++++++++++++------ crates/compose/src/eval.rs | 51 +++++-- crates/core/src/layer/curvature_detail.rs | 8 ++ 3 files changed, 167 insertions(+), 52 deletions(-) diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index c2dfe755..7b6014e0 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -1,5 +1,6 @@ //! The baked curvature map at the detail sizes of curvature generators, built once per map and layout. +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use rayon::prelude::*; @@ -11,52 +12,55 @@ use crate::eval::{Inputs, blur}; /// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. pub struct CurvatureSizes { - pub levels: Vec, + /// One per blurred size, built once a generator gives that size a weight above 0. + pub levels: Vec>>, } -/// Built sizes by the curvature data they come from, the working texture size, the UV tile block and the tiles' scales. -type CacheEntry = (Weak>, (u32, u32), (u32, u32), BlockScales, Arc); +/// The bake map size, its UV tile block and the working texture size a cache entry was built for. +type CacheKey = ((u32, u32), (u32, u32), (u32, u32)); + +/// Built sizes by the curvature data they come from, their layout and the tiles' scales. +type CacheEntry = (Weak>, CacheKey, BlockScales, Arc); static CACHE: Mutex> = Mutex::new(Vec::new()); impl CurvatureSizes { - /// The sizes of the texture set `inp` composites (None without a baked curvature map). - pub fn of(inp: &Inputs) -> Option> { + /// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size. + pub fn of(inp: &Inputs, needed: &[bool]) -> Option> { let curvature = inp.baked.maps.get(&BakedMap::Curvature)?; let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); + if !needed.contains(&true) || width == 0 || height == 0 { + return None; + } + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); let block = grid.map_or((width, height), |grid| (width / grid.cols.max(1), height / grid.rows.max(1))); - let working_size = (inp.gbuf.width, inp.gbuf.height); - - let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - cache.retain(|(source, ..)| source.strong_count() > 0); - let same_source = |source: &Weak>| source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)); - let cached = cache.iter().find(|(source, cached_size, cached_block, cached_scales, _)| { - same_source(source) && *cached_size == working_size && *cached_block == block && *cached_scales == inp.block_scales - }); - if let Some((.., sizes)) = cached { + let key = ((width, height), block, (inp.gbuf.width, inp.gbuf.height)); + let built = cached(curvature, key, &inp.block_scales); + if let Some(sizes) = built.as_ref().filter(|sizes| sizes.holds(needed)) { return Some(sizes.clone()); } - // Covered working texels mark where they land in the bake atlas - let mut covered = vec![false; (width * height) as usize]; - for texel in (0..working_size.0 * working_size.1).filter(|texel| inp.gbuf.covered(*texel as usize)) { - let uv = [((texel % working_size.0) as f32 + 0.5) / working_size.0 as f32, ((texel / working_size.0) as f32 + 0.5) / working_size.1 as f32]; - if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) { - let (baked_x, baked_y) = ((baked_uv[0] * width as f32) as u32, (baked_uv[1] * height as f32) as u32); - if let Some(slot) = covered.get_mut((baked_y.min(height - 1) * width + baked_x.min(width - 1)) as usize) { - *slot = true; - } - } - } - - let sizes = Arc::new(CurvatureSizes::build(curvature, (width, height), &covered, block)); - cache.push((Arc::downgrade(curvature), working_size, block, inp.block_scales.clone(), sizes.clone())); - Some(sizes) + // Built without the cache locked: the build runs parallel work, and a thread waiting on it may composite a tile that asks the cache again + let covered = covered_texels(inp, (width, height)); + let sizes = CurvatureSizes::build(curvature, (width, height), &covered, block, needed, built.as_deref()); + Some(store(curvature, key, &inp.block_scales, sizes)) } - /// Pad `curvature` from its `covered` texels within each UV tile `block`, then blur each block at every size. - fn build(curvature: &[f32], (width, height): (u32, u32), covered: &[bool], block: (u32, u32)) -> CurvatureSizes { + /// Whether every size `needed` marks is built. + fn holds(&self, needed: &[bool]) -> bool { + needed.iter().zip(&self.levels).all(|(needs, level)| !needs || level.is_some()) + } + + /// Pad `curvature` from its `covered` texels within each UV tile `block`, then blur each block at the sizes `needed` marks; sizes already in `built` are kept as they are. + fn build( + curvature: &[f32], + (width, height): (u32, u32), + covered: &[bool], + block: (u32, u32), + needed: &[bool], + built: Option<&CurvatureSizes>, + ) -> CurvatureSizes { let padding = DilationMap::in_rectangular_blocks(covered, width, height, None, block); let deviation: Vec = padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect(); @@ -65,7 +69,15 @@ impl CurvatureSizes { let levels = CurvatureDetail::SIZES .iter() .skip(1) - .map(|size| { + .enumerate() + .map(|(level, size)| { + if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) { + return Some(existing); + } + if !needed.get(level).copied().unwrap_or(false) { + return None; + } + // Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32; let step = (radius / 2).max(1).next_power_of_two(); @@ -77,13 +89,55 @@ impl CurvatureSizes { blur_block(&mut blurred, width, region, radius); } } - coarsen(&blurred, (width, height), step) + Some(Arc::new(coarsen(&blurred, (width, height), step))) }) .collect(); CurvatureSizes { levels } } } +/// The cached sizes of `curvature` for layout `key` and tile `scales`, if any. +fn cached(curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> Option> { + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.retain(|(source, ..)| source.strong_count() > 0); + cache.iter().find(|entry| is_entry_for(entry, curvature, key, scales)).map(|(.., sizes)| sizes.clone()) +} + +/// Cache `sizes`, keeping the sizes another thread cached meanwhile, and return what the cache holds now. +fn store(curvature: &Arc>, key: CacheKey, scales: &BlockScales, sizes: CurvatureSizes) -> Arc { + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let Some((.., cached_sizes)) = cache.iter_mut().find(|entry| is_entry_for(entry, curvature, key, scales)) else { + let sizes = Arc::new(sizes); + cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone())); + return sizes; + }; + + let levels = cached_sizes.levels.iter().zip(sizes.levels).map(|(cached, built)| cached.clone().or(built)).collect(); + *cached_sizes = Arc::new(CurvatureSizes { levels }); + cached_sizes.clone() +} + +/// Whether cache `entry` holds the sizes of `curvature` for layout `key` and tile `scales`. +fn is_entry_for((source, cached_key, cached_scales, _): &CacheEntry, curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> bool { + source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)) && *cached_key == key && cached_scales == scales +} + +/// The bake atlas texels (`width × height`) that the covered working texels of `inp` land on. +fn covered_texels(inp: &Inputs, (width, height): (u32, u32)) -> Vec { + let working_size = (inp.gbuf.width, inp.gbuf.height); + let covered: Vec = (0..width * height).map(|_| AtomicBool::new(false)).collect(); + (0..working_size.0 * working_size.1).into_par_iter().filter(|texel| inp.gbuf.covered(*texel as usize)).for_each(|texel| { + let uv = [((texel % working_size.0) as f32 + 0.5) / working_size.0 as f32, ((texel / working_size.0) as f32 + 0.5) / working_size.1 as f32]; + if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) { + let (baked_x, baked_y) = ((baked_uv[0] * width as f32) as u32, (baked_uv[1] * height as f32) as u32); + if let Some(slot) = covered.get((baked_y.min(height - 1) * width + baked_x.min(width - 1)) as usize) { + slot.store(true, Ordering::Relaxed); + } + } + }); + covered.into_iter().map(AtomicBool::into_inner).collect() +} + /// Blur the `(x0, y0, w, h)` block of `data` (`width` texels per row) in place, reading nothing outside it. fn blur_block(data: &mut [f32], width: u32, (x0, y0, w, h): (u32, u32, u32, u32), radius: u32) { let mut block: Vec = @@ -122,12 +176,40 @@ mod tests { #[test] fn padding_keeps_an_island_border_from_reading_flat() { - let left_half = |texel: u32| texel % 64 < 32; - let curvature: Vec = (0..64 * 64).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect(); - let covered: Vec = (0..64 * 64).map(left_half).collect(); - let sizes = CurvatureSizes::build(&curvature, (64, 64), &covered, (64, 64)); - for level in &sizes.levels { - assert!((level.sample(31, 32) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it"); + let map_size: u32 = 64; + let left_half = |texel: u32| texel % map_size < map_size / 2; + let curvature: Vec = (0..map_size * map_size).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect(); + let covered: Vec = (0..map_size * map_size).map(left_half).collect(); + let shape = (map_size, map_size); + let sizes = CurvatureSizes::build(&curvature, shape, &covered, shape, &[true; CurvatureDetail::BLURRED_SIZES], None); + + // The last covered column, halfway down + let (border_x, border_y) = (map_size / 2 - 1, map_size / 2); + for level in sizes.levels.iter().flatten() { + assert!((level.sample(border_x, border_y) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it"); + } + } + + #[test] + fn sizes_built_on_demand_match_a_full_build() { + let map_size: u32 = 64; + let curvature: Vec = + (0..map_size * map_size).map(|texel| 0.5 + 0.4 * ((texel % map_size) as f32 * 0.3).sin() * ((texel / map_size) as f32 * 0.2).cos()).collect(); + let covered = vec![true; (map_size * map_size) as usize]; + let shape = (map_size, map_size); + let all = vec![true; CurvatureDetail::BLURRED_SIZES]; + let full = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, None); + + let even: Vec = (0..all.len()).map(|level| level % 2 == 0).collect(); + let partial = CurvatureSizes::build(&curvature, shape, &covered, shape, &even, None); + assert!(partial.levels.iter().zip(&even).all(|(level, needed)| level.is_some() == *needed), "only the needed sizes are built"); + + let completed = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, Some(&partial)); + for ((built, expected), earlier) in completed.levels.iter().zip(&full.levels).zip(&partial.levels) { + assert_eq!(built.as_ref().map(|level| &level.deviation), expected.as_ref().map(|level| &level.deviation), "the same values either way"); + if let (Some(built), Some(earlier)) = (built, earlier) { + assert!(Arc::ptr_eq(built, earlier), "sizes already built are kept, not rebuilt"); + } } } } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 1eb29882..e8fd391b 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -771,28 +771,48 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 if tiles.is_empty() || inp.gbuf.width == 0 { return out; } - let res = inp.gbuf.width; + + let working_width = inp.gbuf.width; let mut order = Vec::new(); draw_order(inp.project, list, 0, &mut order); + prepare_curvature_sizes(inp, &order); + for id in order { let Some(layer) = inp.project.content_layer(id) else { continue }; - if let Some(m) = layer_mask(inp.project, id).filter(|m| m.enabled && neighbourhood(&m.effects, res).is_some()) - && let Some(f) = field(inp, channels, &out, id, Job::Mask(m), tiles) + + if let Some(mask) = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()) + && let Some(filtered) = field(inp, channels, &out, id, Job::Mask(mask), tiles) { - out.insert(FieldKey::Mask(id), f); + out.insert(FieldKey::Mask(id), filtered); } - if layer.is_group() || neighbourhood(&layer.content_effects, res).is_none() { + + if layer.is_group() || neighbourhood(&layer.content_effects, working_width).is_none() { continue; } - for ch in channels.iter().filter(|c| layer.channels.contains_key(c)) { - if let Some(f) = field(inp, channels, &out, id, Job::Content(*ch), tiles) { - out.insert(FieldKey::Content(id, *ch), f); + for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) { + if let Some(filtered) = field(inp, channels, &out, id, Job::Content(*channel), tiles) { + out.insert(FieldKey::Content(id, *channel), filtered); } } } out } +/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. +fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { + let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; + let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); + let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); + for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { + if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind { + for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) { + *slot |= in_use; + } + } + } + CurvatureSizes::of(inp, &needed); +} + struct Node<'a> { id: LayerId, content: Content<'a>, @@ -810,7 +830,7 @@ struct Node<'a> { /// Plans of the visible effects of a stack: mask effects (`channel` None) or the content /// effects of one channel (paint effects then read that channel's pixels). -fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, channel: Option) -> Vec> { +fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { effects .iter() .filter(|effect| effect.visible) @@ -819,14 +839,17 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, c Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; - let reads_detail = matches!(&effect.kind, EffectKind::Generator(generator) if generator.detail.is_some()); + let curvature_sizes = match &effect.kind { + EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), + _ => None, + }; EffectPlan { kind: &effect.kind, blend: effect.blend, opacity: effect.opacity, - data: if effect.kind.painted() { tile_of(inp, image, tx, ty, channel) } else { None }, + data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), - curvature_sizes: if reads_detail { CurvatureSizes::of(inp) } else { None }, + curvature_sizes, } }) .collect() @@ -1215,7 +1238,9 @@ impl<'a, 'b> Texel<'a, 'b> { let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); - let blurred = |index: usize| curvature_sizes.and_then(|sizes| sizes.levels.get(index)).map_or(0.0, |level| level.sample(baked_x, baked_y)); + let blurred = |index: usize| { + curvature_sizes.and_then(|sizes| sizes.levels.get(index)).and_then(Option::as_deref).map_or(0.0, |level| level.sample(baked_x, baked_y)) + }; let (mut edges, mut cavities) = (0.0f32, 0.0f32); for (index, (size, weight)) in CurvatureDetail::SIZES.iter().zip(detail.weights).enumerate() { let deviation = if index == 0 { curvature - 0.5 } else { blurred(index - 1) }; diff --git a/crates/core/src/layer/curvature_detail.rs b/crates/core/src/layer/curvature_detail.rs index 826b9823..75c9d36a 100644 --- a/crates/core/src/layer/curvature_detail.rs +++ b/crates/core/src/layer/curvature_detail.rs @@ -19,6 +19,14 @@ impl CurvatureDetail { /// Mostly the finer sizes, tuned the same way: worn edges are thin lines. pub const EDGE_WEIGHTS: [f32; 7] = [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0]; + + /// How many sizes are blurred copies of the map (all but the first). + pub const BLURRED_SIZES: usize = CurvatureDetail::SIZES.len() - 1; + + /// Which blurred sizes this detail reads: those with a weight above 0. + pub fn blurred_sizes_in_use(&self) -> [bool; CurvatureDetail::BLURRED_SIZES] { + std::array::from_fn(|blurred| self.weights.get(blurred + 1).is_some_and(|weight| *weight > 0.0)) + } } impl Default for CurvatureDetail { From 346a0b24f53339015d6c173d038d7059e6fa94ea Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 00:26:26 +0000 Subject: [PATCH 44/73] Bake visualization: test every branch of VertexReach::missed A table over distance starts (painted amount 1 and 2) and a cage-mesh start covers both inclusive ends of the ray range, a name mismatch and Ignore Backface both ways. Also test a request with no high poly. --- crates/bake/src/test/high_poly_reach.rs | 24 ++++++++++++ crates/bake/src/test/vertex_reach.rs | 51 +++++++++++++++++++++++++ crates/bake/src/tests.rs | 3 ++ 3 files changed, 78 insertions(+) create mode 100644 crates/bake/src/test/vertex_reach.rs diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs index bb8753f8..e6d66d07 100644 --- a/crates/bake/src/test/high_poly_reach.rs +++ b/crates/bake/src/test/high_poly_reach.rs @@ -196,3 +196,27 @@ fn matching_by_mesh_name_misses_the_parts_with_another_name() { ); } } + +#[test] +fn without_a_high_poly_no_vertex_has_a_reach() { + let low = primitives::plane(1.0, 4); + let low_bvh = Bvh::new(&low); + let bake_settings = settings(16, &[BakedMap::Normal]); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + + let reach = HighPolyReach::new(&request).unwrap(); + assert!(reach.vertices.is_empty()); + // Any cage distances: there is no vertex to miss + assert_eq!(reach.missed(0, 0.02, 0.01), None); +} diff --git a/crates/bake/src/test/vertex_reach.rs b/crates/bake/src/test/vertex_reach.rs new file mode 100644 index 00000000..7675e8dc --- /dev/null +++ b/crates/bake/src/test/vertex_reach.rs @@ -0,0 +1,51 @@ +use crate::{RayStart, VertexReach}; +use texturecraft_geom::glam::Vec3; + +/// Cage distances in world units; every case's ray runs down the Y axis from 0.5 to -0.25 +const FRONTAL: f32 = 0.5; +const REAR: f32 = 0.25; + +/// A frontal distance a cage-mesh start must ignore: its ray starts on the cage +const IGNORED_FRONTAL: f32 = 9.0; + +/// How far past an end of the ray's range a vertex counts as outside it +const PAST_THE_END: f32 = 1e-3; + +/// A vertex at `height` above the low-poly point at the origin, its triangles facing `facing` +fn vertex(start: RayStart, height: f32, facing: Vec3, name_matches: bool) -> VertexReach { + VertexReach { low_position: Vec3::ZERO, start, high_position: Vec3::new(0.0, height, 0.0), high_facing: facing, name_matches } +} + +#[test] +fn a_vertex_is_missed_outside_the_ray_range_on_another_part_or_facing_away() { + // A painted cage amount of 2 doubles the frontal distance + let starts = [ + (RayStart::Distance { up: Vec3::Y, scale: 1.0 }, FRONTAL), + (RayStart::Distance { up: Vec3::Y, scale: 2.0 }, FRONTAL / 2.0), + (RayStart::CageMesh(Vec3::new(0.0, -FRONTAL, 0.0)), IGNORED_FRONTAL), + ]; + let (top, bottom) = (FRONTAL, -REAR); + // Height, facing, name matches, ignore backface: missed + let cases = [ + (top, Vec3::Y, true, false, false), + (bottom, Vec3::Y, true, false, false), + (0.0, Vec3::Y, true, false, false), + (top + PAST_THE_END, Vec3::Y, true, false, true), + (bottom - PAST_THE_END, Vec3::Y, true, false, true), + (0.0, Vec3::Y, false, false, true), + (0.0, Vec3::NEG_Y, true, false, false), + (0.0, Vec3::NEG_Y, true, true, true), + (0.0, Vec3::Y, true, true, false), + ]; + + for (start, frontal) in starts { + for (height, facing, name_matches, ignore_backface, missed) in cases { + let reach = vertex(start, height, facing, name_matches); + assert_eq!( + reach.missed(frontal, REAR, ignore_backface), + missed, + "{start:?} at height {height}, facing {facing}, name matches {name_matches}, ignore backface {ignore_backface}" + ); + } + } +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index c834da7a..abfccaac 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -29,6 +29,9 @@ mod normal_map_curvature; #[path = "test/tile_selection.rs"] mod tile_selection; +#[path = "test/vertex_reach.rs"] +mod vertex_reach; + fn settings(resolution: u32, maps: &[BakedMap]) -> BakeSettings { with_rays( { From e2a69c4d121de6260443b871819e3cf077e2625d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:15:26 +0000 Subject: [PATCH 45/73] Filter picker: Add filter opens the picker, same-id set edits in place Add filter still adds a neutral HSL filter, and its slot now opens the picker straight away; Esc keeps the HSL and one undo removes it. effect.set naming the filter the effect already is edits its parameters instead of rebuilding it from defaults. The picker's filter list is worked out once. The slot cuts long names short between the thumbnail and the caret, stays highlighted while its picker is open and shows an outline while it has keyboard focus. More engine tests: a swap on a mask, an explicit name, refused swaps leave no change and no undo step. --- crates/engine/src/filter_lib.rs | 7 +++ crates/engine/src/mask_cmds.rs | 12 ++++- crates/engine/tests/filter_swap.rs | 61 ++++++++++++++++++++++++- crates/ui-egui/src/dock.rs | 12 ++++- crates/ui-egui/src/filter_slot.rs | 65 +++++++++++++++++++++------ crates/ui-egui/tests/filter_picker.rs | 54 ++++++++++++++++++++-- 6 files changed, 190 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index 0f0fd952..7856f565 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -26,6 +26,13 @@ impl FilterDef { } } +/// The library entries that build filter effects, in shelf order, worked out once +pub fn filter_effects() -> &'static [&'static FilterDef] { + static FILTER_EFFECTS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| FILTERS.iter().filter(|def| def.is_filter_effect()).collect()); + &FILTER_EFFECTS +} + const fn def(id: &'static str, label: &'static str, group: &'static str, mask: bool) -> FilterDef { FilterDef { id, label, group, mask } } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index bd545fbc..97003298 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity), level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", has_layer, set ), @@ -435,7 +435,9 @@ fn set(s: &mut Session, p: &Value) -> Result { _ => None, }; + // Naming the filter the effect already is edits its parameters like a plain effect.set let swapped = match strp(p, "filter") { + Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(s, effect) == Some(def.id)) => None, Some(filter) => Some(swapped_filter(s, effect, filter, p)?), None => None, }; @@ -492,6 +494,14 @@ fn set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// The library id of the filter effect `effect` is, if it is one +fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> { + match &s.doc.project.effect(effect)?.1.kind { + EffectKind::Filter(filter) => crate::filter_lib::find(filter.label()).map(|def| def.id), + _ => None, + } +} + /// Filter `id` built with `p` and its label, to replace filter effect `effect` fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(EffectKind, &'static str)> { const CMD: &str = "effect.set"; diff --git a/crates/engine/tests/filter_swap.rs b/crates/engine/tests/filter_swap.rs index 87341c60..ed39fa6e 100644 --- a/crates/engine/tests/filter_swap.rs +++ b/crates/engine/tests/filter_swap.rs @@ -78,7 +78,65 @@ fn a_mask_refuses_a_content_only_filter() { assert!(err.to_string().contains("not on masks"), "{err}"); assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert))); - execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).expect("a mask takes a filter that works on masks"); +} + +#[test] +fn a_mask_filter_swaps_in_place_on_the_mask() { + let mut s = session(); + let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + let above = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4})).unwrap(); + + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur"})).unwrap(); + + let blur = effect(&s, swapped); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { .. })), "{:?}", blur.kind); + assert_eq!((blur.name.as_str(), blur.blend, blur.opacity), ("Blur", BlendMode::Multiply, 0.4)); + let layer = s.selected_layer().unwrap(); + let mask_order: Vec = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect(); + assert_eq!(mask_order, vec![below, swapped, above]); +} + +#[test] +fn naming_the_current_filter_edits_it_in_place() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "blur", "target": "content", "radius": 5.0})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur", "radius": 9.0})).unwrap(); + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).unwrap(); + + let blur = effect(&s, id); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 9.0), "the radius is kept, not reset: {:?}", blur.kind); +} + +#[test] +fn a_name_given_with_the_swap_wins() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold", "name": "Edges"})).unwrap(); + + let swapped = effect(&s, id); + assert!(matches!(swapped.kind, EffectKind::Filter(Filter::Threshold { .. })), "{:?}", swapped.kind); + assert_eq!(swapped.name, "Edges"); +} + +#[test] +fn a_refused_swap_changes_nothing_and_adds_no_undo_step() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + execute(&mut s, "effect.set", &json!({"effect": id.0, "blend": "Multiply", "opacity": 0.4, "name": "Flip"})).unwrap(); + let before = effect(&s, id); + + for refused in [json!({"effect": id.0, "filter": "grayscale"}), json!({"effect": id.0, "filter": "nope"}), json!({"effect": id.0, "filter": "levels"})] { + assert!(execute(&mut s, "effect.set", &refused).is_err(), "{refused}"); + } + + assert_eq!(effect(&s, id), before); + // The last step is still the blend, opacity and name edit + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(effect(&s, id).name, "Invert"); } #[test] @@ -88,6 +146,7 @@ fn only_filter_effects_swap_and_only_to_filters() { let filter = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "blur"})).is_err(), "levels is not a filter effect"); + assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "nope"})).is_err(), "an unknown filter on levels"); assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "matFinishGrind"})).is_err(), "a material finish is a fill"); assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "nope"})).is_err()); assert!(matches!(effect(&s, filter).kind, EffectKind::Filter(Filter::Invert))); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 13604e91..4931d071 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -19,7 +19,7 @@ use crate::state::PropsTab; use crate::theme::{Tokens, caption}; use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit}; -/// The filter Add filter adds: at its defaults it changes nothing until the slot swaps it +/// The filter Add filter adds: at its defaults it changes nothing, and its slot opens the picker to swap it const NEW_FILTER: &str = "hsl"; const FILTER_SWATCH_WIDTH: f32 = 36.0; const FILTER_HINT_SIZE: f32 = 10.5; @@ -240,7 +240,15 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { if app.session.selected_layer() != Some(layer.id) { app.run("layer.select", json!({"layer": layer.id.0})); } - app.run(command, with(¶ms, json!({"layer": layer.id.0}))); + + let added = app.run(command, with(¶ms, json!({"layer": layer.id.0}))); + // The neutral filter is a placeholder: its slot opens the picker to choose the real one + if command == "effect.add.filter" + && let Some(effect) = added.as_ref().and_then(|result| result["effect"].as_u64()) + { + crate::filter_slot::open_picker_when_shown(ui.ctx(), effect); + } + ui.close(); } } diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index 7a143612..bf169e22 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -4,7 +4,7 @@ use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::json; use texturecraft_engine::core::{Filter, LayerId}; -use texturecraft_engine::filter_lib::{FILTERS, find}; +use texturecraft_engine::filter_lib::{filter_effects, find}; use crate::TextureCraftApp; use crate::i18n::tr; @@ -13,9 +13,11 @@ use crate::resource_picker_item::ResourcePickerItem; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; use crate::thumbs::Thumbs; +use crate::widgets::elided; const SLOT_HEIGHT: f32 = 52.0; const SLOT_ROUNDING: f32 = 3.0; +const BORDER_WIDTH: f32 = 1.0; const THUMBNAIL_SIZE: f32 = 40.0; const THUMBNAIL_INSET: f32 = 6.0; const CAPTION_FONT_SIZE: f32 = 11.0; @@ -24,6 +26,8 @@ const NAME_FONT_SIZE: f32 = 13.0; const LINE_GAP: f32 = 15.0; const CARET_INSET: f32 = 14.0; const CARET_FONT_SIZE: f32 = 14.0; +/// Gap between the slot and its keyboard focus outline +const FOCUS_MARGIN: f32 = 2.0; /// The slot of filter effect `effect`: a pick runs `effect.set {filter}`, masks offer only mask filters pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: &Filter) { @@ -35,17 +39,21 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name)); - paint(ui, rect, response.hovered(), thumbnail.as_ref(), name); let popup = ui.make_persistent_id(("filter_picker", effect)); - if response.clicked() { + let open_requested = take_open_request(&ctx, effect); + + if response.clicked() || (open_requested && !egui::Popup::is_id_open(&ctx, popup)) { resource_picker::toggle(&ctx, popup); } + let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup); + paint(ui, rect, highlighted, response.has_focus(), thumbnail.as_ref(), name); + let items = |thumbs: &mut Thumbs| { - FILTERS + filter_effects() .iter() - .filter(|def| def.is_filter_effect() && (def.mask || !on_mask)) + .filter(|def| def.mask || !on_mask) .map(|def| ResourcePickerItem { id: def.id, label: tr(def.label), group: tr(def.group), thumbnail: thumbs.filter(&ctx, def.id) }) .collect() }; @@ -55,6 +63,26 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: } } +/// Has the slot of filter effect `effect` open its picker if it shows this frame or the next, as Add filter does for the filter it adds +pub(crate) fn open_picker_when_shown(ctx: &egui::Context, effect: u64) { + let frame = ctx.cumulative_frame_nr(); + ctx.data_mut(|data| data.insert_temp(open_request_id(), (effect, frame))); +} + +/// Whether an open request for `effect`'s slot is waiting, removing it; a request older than a frame lapses +fn take_open_request(ctx: &egui::Context, effect: u64) -> bool { + let frame = ctx.cumulative_frame_nr(); + let request = ctx.data_mut(|data| data.remove_temp::<(u64, u64)>(open_request_id())); + + // Properties can draw before or after the menu that asked, so a request lives for this frame and the next + request.is_some_and(|(requested_effect, requested_frame)| requested_effect == effect && frame <= requested_frame + 1) +} + +/// Where the effect whose slot should open its picker waits +fn open_request_id() -> egui::Id { + egui::Id::new("filter_slot_open_request") +} + /// Whether filter effect `effect` sits in a mask rather than the layer content fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { let project = &app.session.doc.project; @@ -62,22 +90,31 @@ fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { owner.and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|masked| masked.id.0 == effect)) } -/// The slot's box: thumbnail, "Filter" over the name, caret -fn paint(ui: &Ui, rect: Rect, hovered: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) { +/// The slot's box, highlighted while hovered or its picker is open and outlined while focused: thumbnail, "Filter" over the name, caret +fn paint(ui: &Ui, rect: Rect, highlighted: bool, focused: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) { let tk = Tokens::get(ui.ctx()); let painter = ui.painter(); - let (fill, border) = if hovered { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; - painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(1.0, border), egui::StrokeKind::Inside); + let (fill, border) = if highlighted { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; + painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(BORDER_WIDTH, border), egui::StrokeKind::Inside); + if focused { + painter.rect_stroke(rect.expand(FOCUS_MARGIN), SLOT_ROUNDING, ui.visuals().selection.stroke, egui::StrokeKind::Outside); + } if let Some(texture) = thumbnail { let image = Rect::from_min_size(pos2(rect.left() + THUMBNAIL_INSET, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); painter.image(texture.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); } - let center = rect.center(); - painter.text(center - vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, tr("Filter"), FontId::proportional(CAPTION_FONT_SIZE), tk.text_dim); - painter.text(center + vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, name, FontId::proportional(NAME_FONT_SIZE), tk.text_strong); + // Long names are cut short rather than run under the thumbnail or the caret + let text_left = rect.left() + THUMBNAIL_INSET * 2.0 + THUMBNAIL_SIZE; + let text_right = rect.right() - CARET_INSET * 2.0; + let text_center_x = (text_left + text_right) * 0.5; + let lines = [(tr("Filter"), CAPTION_FONT_SIZE, tk.text_dim, -LINE_GAP * 0.5), (name, NAME_FONT_SIZE, tk.text_strong, LINE_GAP * 0.5)]; + for (text, size, color, offset) in lines { + let galley = elided(painter, text, size, color, text_right - text_left); + painter.galley(pos2(text_center_x, rect.center().y + offset) - galley.size() * 0.5, galley, color); + } - let caret_color = if hovered { tk.text } else { tk.text_dim }; - painter.text(pos2(rect.right() - CARET_INSET, center.y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color); + let caret_color = if highlighted { tk.text } else { tk.text_dim }; + painter.text(pos2(rect.right() - CARET_INSET, rect.center().y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color); } diff --git a/crates/ui-egui/tests/filter_picker.rs b/crates/ui-egui/tests/filter_picker.rs index 31daef69..819dcc25 100644 --- a/crates/ui-egui/tests/filter_picker.rs +++ b/crates/ui-egui/tests/filter_picker.rs @@ -66,16 +66,64 @@ fn escape_closes_the_picker_without_changes() { assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); } -#[test] -fn add_filter_adds_a_filter_and_selects_it() { - let (mut harness, _) = app_with_invert(); +/// Opens the wand's Add effect menu and clicks Add filter +fn add_filter_from_the_wand(harness: &mut Harness<'_, TextureCraftApp>) { harness.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); harness.run_steps(3); harness.get_by_label("Add filter").click(); harness.run_steps(3); +} + +#[test] +fn add_filter_adds_a_filter_selects_it_and_opens_its_picker() { + let (mut harness, _) = app_with_invert(); + add_filter_from_the_wand(&mut harness); let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Properties shows the new filter's slot"); + assert!(egui::Popup::is_any_open(&harness.ctx), "the new filter's picker is open to choose the real filter"); + + // The search field has the focus, and a search brings Sharpen into view + harness.event(egui::Event::Text("sharp".into())); + harness.run_steps(3); + harness.get_by_label("Sharpen").click(); + harness.run_steps(3); + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, added)); +} + +#[test] +fn escape_after_add_filter_keeps_the_neutral_filter() { + let (mut harness, _) = app_with_invert(); + add_filter_from_the_wand(&mut harness); + assert!(harness.query_by_label("Sharpen").is_some(), "Add filter opened the picker"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter stays selected") }; + assert!(!egui::Popup::is_any_open(&harness.ctx)); + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + + harness.state_mut().run("edit.undo", Value::Null); + assert!(harness.state().session.doc.project.effect(added).is_none(), "one undo removes the neutral filter"); +} + +#[test] +fn add_filter_on_a_mask_adds_it_to_the_mask() { + let (mut harness, _) = app_with_invert(); + let layer = harness.state().session.selected_layer().unwrap(); + // A new mask becomes the selected target, so the wand adds to it + harness.state_mut().run("mask.add.white", json!({"layer": layer.0})); + harness.run_steps(3); + + add_filter_from_the_wand(&mut harness); + + let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; + let mask = harness.state().session.doc.project.layer(layer).unwrap().mask.clone().unwrap(); + assert!(mask.effects.iter().any(|effect| effect.id == added), "the filter went on the mask"); + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + assert!(harness.query_by_label("Sharpen").is_some(), "the mask filter's picker is open"); + assert!(harness.query_by_label("Grayscale").is_none(), "the picker leaves out content-only filters"); } From c39d95b4c8a53da5791d513c76c8ae00e761de89 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:21:42 +0000 Subject: [PATCH 46/73] Filter swap: test that invalid parameters for the new filter are refused --- crates/engine/tests/filter_swap.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/filter_swap.rs b/crates/engine/tests/filter_swap.rs index ed39fa6e..27103ab4 100644 --- a/crates/engine/tests/filter_swap.rs +++ b/crates/engine/tests/filter_swap.rs @@ -129,7 +129,12 @@ fn a_refused_swap_changes_nothing_and_adds_no_undo_step() { execute(&mut s, "effect.set", &json!({"effect": id.0, "blend": "Multiply", "opacity": 0.4, "name": "Flip"})).unwrap(); let before = effect(&s, id); - for refused in [json!({"effect": id.0, "filter": "grayscale"}), json!({"effect": id.0, "filter": "nope"}), json!({"effect": id.0, "filter": "levels"})] { + for refused in [ + json!({"effect": id.0, "filter": "grayscale"}), + json!({"effect": id.0, "filter": "nope"}), + json!({"effect": id.0, "filter": "levels"}), + json!({"effect": id.0, "filter": "colorBalance", "shadows": "not a color"}), + ] { assert!(execute(&mut s, "effect.set", &refused).is_err(), "{refused}"); } From 284cb7d125aa98791d00e529b40b4111cb8eaa90 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:25:04 +0000 Subject: [PATCH 47/73] Refuse host paths in files entries for automation textureSet.meshMap.import takes its paths in files[].path, which authorize_command did not look at, so a control client could import an image from outside --read-root. Treat a path or dir in any files entry like a top-level one, and document that automation imports baked maps through resource_import plus textureSet.meshMap.set. --- crates/automation/src/workspace.rs | 35 ++++++++++++++++++++++-------- docs/control-protocol.md | 6 ++--- 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 2015c090..1061db2d 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -127,20 +127,20 @@ fn file_error(op: &str, path: &str, e: std::io::Error) -> AutomationError { AutomationError::Io(format!("{op} `{path}` failed: {e}")) } -/// Engine commands that take host paths (`file.open`, `file.exportTextures`, `resource.import`, -/// `material.save`, …) would bypass the workspace: automation clients use the workspace-scoped -/// methods instead. Any command given a `path` or `dir` is refused, and every `file.*` command -/// but `file.close` and `file.removeUnused` (`file.save` even without `path`: a headless session's path is -/// workspace-relative, not a host path; `file.reimportMesh` without `path` re-reads the -/// embedded mesh). +/// Host keys a command reads or writes a file through, at the top level or in each `files` entry +const HOST_PATH_KEYS: [&str; 2] = ["path", "dir"]; + +/// Refuses engine commands that would reach host paths around the workspace roots, so clients use the workspace tools pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> { - let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null())); - let ok = match id { + let has_path = names_host_path(params) || params.get("files").and_then(Value::as_array).is_some_and(|files| files.iter().any(names_host_path)); + + // `file.save` is refused even without a path: a headless session's path is workspace-relative, not a host path + let allowed = match id { "file.close" | "file.removeUnused" => true, "file.reimportMesh" => !has_path, _ => !id.starts_with("file.") && !has_path, }; - if ok { + if allowed { Ok(()) } else { Err(bad(format!( @@ -149,6 +149,11 @@ pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError } } +/// Whether `params` names a host path or folder at its own top level +fn names_host_path(params: &Value) -> bool { + HOST_PATH_KEYS.iter().any(|key| params.get(key).is_some_and(|value| !value.is_null())) +} + #[cfg(test)] mod tests { use super::*; @@ -243,6 +248,18 @@ mod tests { assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok()); } + #[test] + fn nested_file_paths_are_denied() { + let outside_file = json!({"files": [{"path": "/etc/x_ao.png", "map": "ao"}]}); + assert!(authorize_command("textureSet.meshMap.import", &outside_file).is_err()); + + let one_of_many = json!({"files": [{"map": "ao"}, {"path": "/etc/x_ao.png"}]}); + assert!(authorize_command("textureSet.meshMap.import", &one_of_many).is_err()); + + let no_paths = json!({"files": [{"map": "ao"}, {"path": null}]}); + assert!(authorize_command("textureSet.meshMap.import", &no_paths).is_ok()); + } + /// Every registry command documenting a host path must be classified (fails when a new /// path-taking command is added without an automation policy). #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 734036ca..079788be 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -153,8 +153,8 @@ print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1 File › Save. Through `command_run`, every `file.*` command but `file.close` and `file.removeUnused` (and -`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir` (`resource.import`, -`material.save`, `material.load`, …), in both modes: use the workspace tools below. `resource.text` +`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir`, at the top level or in +a `files` entry (`resource.import`, `material.save`, `material.load`, `textureSet.meshMap.import`, …), in both modes: use the workspace tools below. `resource.text` takes a font family, not a path: it reads only the system's font folders. | Tool | Params | Notes | @@ -170,7 +170,7 @@ takes a font family, not a path: it reads only the system's font folders. | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | | `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | -| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); many baked map files at once, matched to sets and maps by file name: `textureSet.meshMap.import {files: [{path, map?}]}` | +| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); call it once per baked map file (the desktop app's `textureSet.meshMap.import`, which takes host paths, is refused through `command_run`) | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | | `material_load` | `{path}` | Add a `.tcmat` smart material, a MaterialCraft `.mcmat` material or a `.mcraft` package above the selection | | `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root | From dd7bb51bd531205ace004614e3238a8196d5082e Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:27:58 +0000 Subject: [PATCH 48/73] Bake visualization: pick up the reach even when nothing is drawn The reach job was only polled while the high poly was drawn, so leaving bake mode or hiding the high poly mid-reach kept busy() true and the view repainting every frame. Poll it at the start of every sync. The resend test now waits for the rebuilt cage's reach before checking that a resend starts none, so it no longer depends on thread timing. --- .../ui-egui/src/bake_scene/bake_scene_link.rs | 30 +++++++++++++++++-- crates/ui-egui/src/bake_scene/reach_link.rs | 27 +++++++++-------- 2 files changed, 43 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/bake_scene/bake_scene_link.rs b/crates/ui-egui/src/bake_scene/bake_scene_link.rs index 7f4459c6..b9cecaa9 100644 --- a/crates/ui-egui/src/bake_scene/bake_scene_link.rs +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -47,6 +47,8 @@ impl BakeSceneLink { /// Add to `out` what the GPU needs to draw `visualization` this frame pub fn sync(&mut self, session: &Session, visualization: Option, out: &mut SceneSync) { + self.reach.poll(); + let Some(visualization) = visualization else { return }; if visualization.high_poly { @@ -117,6 +119,10 @@ mod tests { const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None }; + /// How long a test waits for the reach worker: frames, and the pause between them + const WAIT_FRAMES: usize = 2000; + const WAIT_FRAME_PAUSE: std::time::Duration = std::time::Duration::from_millis(5); + /// The sample project with a high poly a little outside its low poly fn session() -> Session { const HIGH_POLY_OFFSET: f32 = 0.02; @@ -143,11 +149,11 @@ mod tests { /// Sync until the reach worked out on the worker thread colors the high poly; the share of vertices drawn red fn red_share(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> f32 { - for _ in 0..2000 { + for _ in 0..WAIT_FRAMES { if let Some((_, missed)) = sync(link, session, visualization).bake_high_missed { return missed.iter().sum::() / missed.len().max(1) as f32; } - std::thread::sleep(std::time::Duration::from_millis(5)); + std::thread::sleep(WAIT_FRAME_PAUSE); } panic!("the reach never arrived"); } @@ -175,6 +181,8 @@ mod tests { texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap(); let rebuilt = sync(&mut link, &session, EVERYTHING); assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage"); + // The rebuilt cage starts a new reach: let it finish so the last check sees only what the resend starts + red_share(&mut link, &session, EVERYTHING); link.resend(); let resent = sync(&mut link, &session, EVERYTHING); @@ -185,6 +193,24 @@ mod tests { assert!(!link.busy(), "a lost frame doesn't work out the reach again"); } + #[test] + fn a_reach_finishes_while_nothing_is_drawn() { + let session = session(); + let no_high_poly = BakeVisualization { high_poly: false, ..EVERYTHING }; + for hidden in [None, Some(no_high_poly)] { + let mut link = BakeSceneLink::default(); + sync(&mut link, &session, EVERYTHING); + assert!(link.busy(), "the first frame starts working out the reach"); + + let finished = (0..WAIT_FRAMES).any(|_| { + std::thread::sleep(WAIT_FRAME_PAUSE); + link.sync(&session, hidden, &mut SceneSync::default()); + !link.busy() + }); + assert!(finished, "the view stops redrawing for a reach once it is done: {hidden:?}"); + } + } + #[test] fn the_red_follows_the_distances_and_the_selected_set() { let (mut session, mut link) = (session(), BakeSceneLink::default()); diff --git a/crates/ui-egui/src/bake_scene/reach_link.rs b/crates/ui-egui/src/bake_scene/reach_link.rs index 45527522..cdf0ca58 100644 --- a/crates/ui-egui/src/bake_scene/reach_link.rs +++ b/crates/ui-egui/src/bake_scene/reach_link.rs @@ -34,6 +34,21 @@ impl ReachLink { self.shown = None; } + /// Pick up the reach once the worker finishes; runs every frame, even when nothing is drawn, so `busy` clears + pub(super) fn poll(&mut self) { + let Some(job) = &self.job else { return }; + + match job.try_recv() { + Ok(reach) => { + self.reach = reach; + self.shown = None; + self.job = None; + } + Err(TryRecvError::Disconnected) => self.job = None, + Err(TryRecvError::Empty) => {} + } + } + /// Start a new reach when the high poly (sent under `high_id`) or a set's inputs changed, and color the high poly when the reach or the distances changed pub(super) fn sync(&mut self, session: &Session, high_id: u64, only_set: Option, out: &mut SceneSync) { let set_count = session.doc.project.texture_sets.len(); @@ -53,18 +68,6 @@ impl ReachLink { (self.keys, self.high_id) = (keys, high_id); } - if let Some(job) = &self.job { - match job.try_recv() { - Ok(reach) => { - self.reach = reach; - self.shown = None; - self.job = None; - } - Err(TryRecvError::Disconnected) => self.job = None, - Err(TryRecvError::Empty) => {} - } - } - // Colors wait for the reach being worked out: the old ones stay until it arrives if self.job.is_some() { return; From 8cdd5dc296eead1c9d6bc884c867bbe9a342294e Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:28:25 +0000 Subject: [PATCH 49/73] Filter slot: use Id::unique for the open request (Id::new is deprecated) --- crates/ui-egui/src/filter_slot.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index bf169e22..172017d9 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -80,7 +80,7 @@ fn take_open_request(ctx: &egui::Context, effect: u64) -> bool { /// Where the effect whose slot should open its picker waits fn open_request_id() -> egui::Id { - egui::Id::new("filter_slot_open_request") + egui::Id::unique("filter_slot_open_request") } /// Whether filter effect `effect` sits in a mask rather than the layer content From cbe3c86acb76e6ddf98b4b77dd4a5eda836ee5a1 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:32:06 +0000 Subject: [PATCH 50/73] Curvature detail: full-strength block borders, neutral raw curvature, stricter sizes Divide each blurred detail size by the share of the blur window inside its UV tile block, so texels near a block or map edge keep their strength instead of fading toward zero. Raw mode reads mid gray when there is no curvature to sample. The size cache keeps one layout per curvature map. Mask previews of hidden layers build their sizes once before the tiles run in parallel. effect.set rejects a sizes array with a non-numeric entry. --- crates/compose/src/curvature_sizes.rs | 77 ++++++++++++++++++++++++--- crates/compose/src/eval.rs | 53 ++++++++++++++---- crates/engine/src/mask_cmds.rs | 8 +-- crates/engine/tests/session.rs | 2 + 4 files changed, 120 insertions(+), 20 deletions(-) diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index 7b6014e0..0d9c3bc9 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -8,7 +8,7 @@ use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail}; use texturecraft_texel::dilate::{DilationMap, NONE}; use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE}; -use crate::eval::{Inputs, blur}; +use crate::eval::{BLUR_BOX_PASSES, Inputs, blur}; /// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. pub struct CurvatureSizes { @@ -107,6 +107,8 @@ fn cached(curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> Opt fn store(curvature: &Arc>, key: CacheKey, scales: &BlockScales, sizes: CurvatureSizes) -> Arc { let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let Some((.., cached_sizes)) = cache.iter_mut().find(|entry| is_entry_for(entry, curvature, key, scales)) else { + // One layout per curvature map: sizes built for an earlier tile layout or working size are dropped with it + cache.retain(|(source, ..)| source.strong_count() > 0 && !std::ptr::eq(source.as_ptr(), Arc::as_ptr(curvature))); let sizes = Arc::new(sizes); cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone())); return sizes; @@ -138,20 +140,47 @@ fn covered_texels(inp: &Inputs, (width, height): (u32, u32)) -> Vec { covered.into_iter().map(AtomicBool::into_inner).collect() } -/// Blur the `(x0, y0, w, h)` block of `data` (`width` texels per row) in place, reading nothing outside it. -fn blur_block(data: &mut [f32], width: u32, (x0, y0, w, h): (u32, u32, u32, u32), radius: u32) { +/// Blur the `(left, top, region_width, region_height)` block of `data` (`width` texels per row) in place, reading nothing outside it. +fn blur_block(data: &mut [f32], width: u32, (left, top, region_width, region_height): (u32, u32, u32, u32), radius: u32) { + let rows = top..top + region_height; let mut block: Vec = - (y0..y0 + h).flat_map(|y| (x0..x0 + w).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect(); - blur(&mut block, w as usize, h as usize, radius as usize); + rows.flat_map(|y| (left..left + region_width).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect(); + blur(&mut block, region_width as usize, region_height as usize, radius as usize); - for (row, values) in block.chunks(w as usize).enumerate() { - let start = ((y0 + row as u32) * width + x0) as usize; + // The blur reads zero past the block's edges; dividing by the share of its window inside the block keeps the edges at full strength + let column_weights = window_inside(region_width as usize, radius as usize); + let row_weights = window_inside(region_height as usize, radius as usize); + for (values, row_weight) in block.chunks_mut(region_width as usize).zip(&row_weights) { + for (value, column_weight) in values.iter_mut().zip(&column_weights) { + *value /= row_weight * column_weight; + } + } + + for (row, values) in block.chunks(region_width as usize).enumerate() { + let start = ((top + row as u32) * width + left) as usize; if let Some(target) = data.get_mut(start..start + values.len()) { target.copy_from_slice(values); } } } +/// The share of the [`blur`] window at each texel of a line `length` long that falls inside it: 1 from three radii in. +fn window_inside(length: usize, radius: usize) -> Vec { + let window = (2 * radius + 1) as f64; + let mut weights = vec![1.0f64; length]; + for _ in 0..BLUR_BOX_PASSES { + let running_totals: Vec = std::iter::once(0.0) + .chain(weights.iter().scan(0.0, |total, weight| { + *total += weight; + Some(*total) + })) + .collect(); + let total_at = |end: usize| running_totals.get(end.min(length)).copied().unwrap_or(0.0); + weights = (0..length).map(|texel| (total_at(texel + radius + 1) - total_at(texel.saturating_sub(radius))) / window).collect(); + } + weights.into_iter().map(|weight| weight as f32).collect() +} + /// `data` averaged over `step × step` squares (the last ones clipped to the map). fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32) -> CurvatureSizeLevel { let (coarse_width, coarse_height) = (width.div_ceil(step), height.div_ceil(step)); @@ -190,6 +219,40 @@ mod tests { } } + #[test] + fn uniform_curvature_keeps_its_strength_at_block_borders() { + let (map_width, map_height): (u32, u32) = (256, 256); + // Curvature 0.8 reads 0.3 above the neutral 0.5 at every size + const CURVATURE: f32 = 0.8; + let expected = CURVATURE - 0.5; + let curvature = vec![CURVATURE; (map_width * map_height) as usize]; + let covered = vec![true; curvature.len()]; + let block = (map_width / 2, map_height); + let sizes = CurvatureSizes::build(&curvature, (map_width, map_height), &covered, block, &[true; CurvatureDetail::BLURRED_SIZES], None); + + // The map's corner, then the last texel of the left block and the first of the right one, halfway down + let border_texels = [(0, 0), (block.0 - 1, map_height / 2), (block.0, map_height / 2)]; + for level in sizes.levels.iter().flatten() { + for (x, y) in border_texels { + assert!((level.sample(x, y) - expected).abs() < 0.01, "texel ({x}, {y}) reads {} instead of the uniform {expected}", level.sample(x, y)); + } + } + } + + #[test] + fn a_new_layout_replaces_the_sizes_of_the_old_one() { + let curvature = Arc::new(vec![0.5; 16]); + let scales = BlockScales::default(); + let entries_for_curvature = || { + let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.iter().filter(|(source, ..)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(&curvature))).count() + }; + + store(&curvature, ((4, 4), (4, 4), (4, 4)), &scales, CurvatureSizes { levels: Vec::new() }); + store(&curvature, ((4, 4), (2, 2), (8, 8)), &scales, CurvatureSizes { levels: Vec::new() }); + assert_eq!(entries_for_curvature(), 1, "only the latest layout of a curvature map stays cached"); + } + #[test] fn sizes_built_on_demand_match_a_full_build() { let map_size: u32 = 64; diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index e8fd391b..3a30c7d3 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -443,6 +443,9 @@ pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) data.par_iter_mut().zip(transpose(&columns, height, width)).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32); } +/// The box blurs `blur` runs along each axis +pub(crate) const BLUR_BOX_PASSES: usize = 3; + /// Three box blurs of radius `r` along every row (`w` long) of `data`. fn blur_rows(data: &mut [i64], w: usize, r: usize) { if w == 0 { @@ -450,7 +453,7 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) { } data.par_chunks_mut(w).for_each(|row| { let mut tmp = vec![0i64; row.len()]; - for _ in 0..3 { + for _ in 0..BLUR_BOX_PASSES { box_line(row, &mut tmp, r); row.copy_from_slice(&tmp); } @@ -800,9 +803,14 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 /// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { - let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); + prepare_mask_curvature_sizes(inp, masks); +} + +/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. +fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator) { + let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind { for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) { @@ -1230,11 +1238,19 @@ impl<'a, 'b> Texel<'a, 'b> { /// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend. fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 { - let Some(curvature) = self.baked(BakedMap::Curvature) else { return 0.0 }; + let combine = |edges: f32, cavities: f32| match detail.mode { + CurvatureMode::Edges => edges, + CurvatureMode::Cavities => cavities, + CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), + CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + }; + + // Without curvature to read the texel is flat: no edges or cavities + let Some(curvature) = self.baked(BakedMap::Curvature) else { return combine(0.0, 0.0) }; let working_size = (self.res, self.inp.gbuf.height); let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; - let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return 0.0 }; + let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return combine(0.0, 0.0) }; let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); @@ -1251,12 +1267,7 @@ impl<'a, 'b> Texel<'a, 'b> { cavities = 1.0 - (1.0 - cavities) * (1.0 - weight * (-response).clamp(0.0, 1.0)); } - match detail.mode { - CurvatureMode::Edges => edges, - CurvatureMode::Cavities => cavities, - CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), - CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), - } + combine(edges, cavities) } fn mask(&mut self, plan: &MaskPlan) -> f32 { @@ -1972,6 +1983,10 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); let coordinates = all_tiles(width, height); + + // A hidden layer's mask is left out of the stack's preparation + prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); + let fields = neighbourhood_fields(inputs, &channels, &coordinates); let tiles: HashMap<(u32, u32), Vec> = coordinates .par_iter() @@ -2025,6 +2040,10 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option